Record Collection JSON

Tell us what’s happening:
Hard stuck. Its saying “Cannot read property ‘push’ of undefined”
plz help

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 (value!==""&&prop=="tracks"){
      collection[id][prop].push(value);           
  } else if(value!==""){ 
      collection[id][prop] = value;    
  } else { 
      delete collection[id][prop];    
  }  
  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_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36.

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

It’s because there’s no tracks property on that object when you’re trying to push. In that case collection[id][props] is undefined, and therefore you can’t use push, because push is an Array method. In this case, you need to assign the property tracks to a new array containing the value. I’ll post just this bit of code below.

if (collection[id].tracks) {  // If tracks already exists
  collection[id].tracks.push(value);   // push it
} else {  // otherwise
  collection[id].tracks = [value];  // assign it
}
1 Like

The error happens because you are trying to oush onto a nonexistent object (null). Check if the array exists before you push. Create it if it doesn’t exist.

1 Like

Thank you! passed it :+1: