Record Collection (Using Conditional Statements)

Tell us what’s happening:
I am having trouble understanding why I am not passing this. I am failing the objective below.

" After updateRecords(5439, "tracks", "Take a Chance on Me") , tracks should have "Take a Chance on Me" as the last element"

I receive an error, “Cannot read property ‘push’ of undefined”, but am unsure of where to go next. Can someone help me better understand the logic behind my future corrections, once they’re analyzed?

Your code so far


// Setup
var collection = {
    "2548": {
      "album": "Slippery When Wet",
      "artist": "Bon Jovi",
      "tracks": [ 
        "Let It Rock", 
        "You Give Love a Bad Name" 
      ]
    },
    "2468": {
      "album": "1999",
      "artist": "Prince",
      "tracks": [ 
        "1999", 
        "Little Red Corvette" 
      ]
    },
    "1245": {
      "artist": "Robert Palmer",
      "tracks": [ ]
    },
    "5439": {
      "album": "ABBA Gold"
    }
};
// Keep a copy of the collection for tests
var collectionCopy = JSON.parse(JSON.stringify(collection));

// Only change code below this line
function updateRecords(id, prop, value) {
  if (prop !=="tracks" && value !=="") {
    collection[id][prop] = value;
  }
  else if (prop =="tracks" && value !=="") {
    collection[id][prop].push(value);
  }
  else if (value =="") {
    delete collection[id][prop];
  }
  else if (prop == "tracks" && "tracks"=="")
    collection[id][prop].unshift(value);
  return collection;
}

// Alter values below to test your code
updateRecords(5439, "artist", "ABBA");

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/record-collection

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

The problem is for the test case above, there is no tracks for that particular album, so you can not push to an array which does not exist. Basically, you are not meeting the following requirement of the challenge instructions.

If prop is "tracks" but the album doesn’t have a "tracks" property, create an empty array before adding the new value to the album’s corresponding property.

You just need to add some extra logic inside the following else if statement.

  else if (prop =="tracks" && value !=="") {
    collection[id][prop].push(value);
  }

Ah, I passed! I added an if statement and else statement within this else if statement to test to see if there was an array and, if not, then add an array (i.e. [value]).

That is good. Technically, you did not need to test if it was an array or not. You only needed to test if the property did not already existed in the object. If could have been as simple as:

if (!collection[id][prop]) {
  collection[id][prop] = [];
}