Cannot add property to object

Tell us what’s happening:
“prop” is returning undefined although i am checking for this issue before i continue in the code.

I tried:

  1. object.id[prop] = value;
  2. object.id.prop = value;
    

Your code so far


// Setup
var collection = {
2548: {
  albumTitle: 'Slippery When Wet',
  artist: 'Bon Jovi',
  tracks: ['Let It Rock', 'You Give Love a Bad Name']
},
2468: {
  albumTitle: '1999',
  artist: 'Prince',
  tracks: ['1999', 'Little Red Corvette']
},
1245: {
  artist: 'Robert Palmer',
  tracks: []
},
5439: {
  albumTitle: 'ABBA Gold'
}
};

// Only change code below this line
function updateRecords(object, id, prop, value) {

  //check if the object is null
  if (object ==null){
      console.log("object is null");
      return false;
  }

  //check if id is not a number
  if (id == null || isNaN(id)){
      console.log("Id is not a number");
      return false;
  }
  
  //check if prop is not a string
  if (prop == null || prop == undefined || typeof prop != 'string'){
      console.log("prop is not a track");
      return false;
  }

  //check if the value is not a string
  if (value == null || typeof value != 'string'){
      console.log("value is not valid word");
      return false;
  }

  object.id.prop = value;

return object;
}

updateRecords(collection, 5439, 'artist', 'ABBA');

Your browser information:

User Agent is: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.66 Safari/537.36.

Challenge: Record Collection

Link to the challenge:

So remember, id is also a variable. collection[id] is going to refer to a particular record. Can you use that to get to a particular property on that object?

2 Likes

You cannot use dot notation with variables holding the desired property name. I think there should be an example of this in a previous lesson.

2 Likes

You are misreading the error:

Uncaught TypeError: Cannot set property ‘prop’ of undefined
at updateRecords

It is not saying that prop is undefined, but that object.id is undefined. That is because id is not the name of the property but a variable holding the name of the property. You need to use bracket notation for both of those variables.

3 Likes