TypeError: Cannot read property 'id' of undefined

I am trying to work around the problem but it seem strange as I am not proficient with JS Objects. Following is my code. What am I doing wrong?


// 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"
}
};

// Only change code below this line
// Only change code below this line
function updateRecords(id, prop, value) {
if(collection.prop['id']['tracks']){
  return true
}else{
  collection.prop.id.tracks = []
}

}

// 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_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36.

Challenge: Record Collection

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

first, dot notation search for an exact match for the name, as there is no property named “prop” in the object, collection.prop is undefined, undefined values do not have properties and trying to access properties on undefined values give an error - so you get an error when you try to do collection.prop["id"] gives an error

same thing for collection.prop.id

but I thought when we don’t know the property name, we can do prop?

there is a way in which you can use a variable to access a property value, but it is not that one.
Also, consider what are the properties of the collection object, and what are the values that the prop variable can have - do they match?

I was trying to match what parameter was passed as arguements, so the id become the number, prop becomes the key and value becomes the value, if that make sense?
Are you saying, we need to hard code inside the function ?

no, you don’t need to hardcode

but look carefully at the collection object, what properties does it have?

you are not proficient with objects but you need to become, take this challenge as a chance to learn how to work with objects - but you will also need to review stuff

for example, how to access properties with a variable

1 Like

and how to access properties in nested objects - as it seems you are having trouble there too

I suggest that you review these challenges:
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/accessing-object-properties-with-dot-notation

https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/accessing-object-properties-with-bracket-notation

https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/accessing-object-properties-with-variables