Need help on Record Collection Code

I’ve been banging my head against the wall for 3 days now and can’t seem to figure out what’s wrong with my code.

The following three tests don’t pass:

  • After updateRecords(collection, 5439, "tracks", "Take a Chance on Me") , tracks should have Take a Chance on Me as the last element.
  • After updateRecords(collection, 1245, "tracks", "Addicted to Love") , tracks should have Addicted to Love as the last element.
  • After updateRecords(collection, 2468, "tracks", "Free") , tracks should have 1999 as the first element.

Any help is highly appreciated.

// Only change code below this line
function updateRecords(object, id, prop, value) {
if(object[id][prop] != 'tracks' && value != '') {
  object[id][prop] = value;
} 

if(prop == 'tracks' && object[id].hasOwnProperty(prop) == false){
  object[id][prop] = [];
  object[id][prop].push(value);
  } 

if(prop === 'tracks' && value != ''){
  object[id][prop].push(value);
}

if(value == ''){
  delete object[id][prop];
}

return object;
}

Link to the challenge:

For updateRecords(collection, 5439, "tracks", "Take a Chance on Me").

if(object['5439']['tracks'] != 'tracks' && 'Take a Chance on Me' != '') {
  object['5439']['tracks'] = 'Take a Chance on Me';
} 

That is saying:

IF THE VALUE OF collection[“5439”][“tracks”] IS NOT “tracks” AND THE STRING “Take a Chance on Me” IS NOT an empty string ASSIGN “Take a Chance on Me” TO collection[“5439”][“tracks”]

So that condition is true, the property is undefined, not the string "tracks". So the first condition you have will always assign object[id][prop] = value. So you end up with:

{
   // ...snip
  5439: {
    albumTitle: 'ABBA Gold',
    tracks: 'Take A Chance on Me'
  },
};

Then the function will error, because the second condition after that says:

if('tracks' === 'tracks' && value != ''){
  object['5439][prop].push(value);
}

So

IF THE VALUE OF THE STRING “tracks” IS “tracks” AND THE VALUE OF THE STRING “Take a Chance on Me” IS NOT AN EMPTY STRING, push THE STRING “Take a Chance on Me” TO collection[“5439”][“tracks”]

You can’t push on a string, so this errors.

You need to fix the first condition, you need to check what the variables passed into the function are, not what you’re currently doing. Once you fix that, you need to use else if otherwise the code will just run every condition that is true – you’re just doing one operation after another (if you leave it as-is, the third if block will run immediately after the second if block)

1 Like

Thank you.

I’ve changed it and now it works.

1 Like