Accessing and modifying nested objects

Hi could anyone explain why the code below works when accessing objects properties with brackets but when using dots it does not work?
For instance : delete records[id][prop]; works but this does not delete records.id.prop;

Why this works: records[id][prop] = value; but this does not records.id.prop = value;

In the previous challenges I’ve been told the brackets were to be used when accessing a property with a space in its name…

  **Your code so far**

// Setup
const recordCollection = {
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(records, id, prop, value) {
if(prop != 'tracks' && value != "") {
  records[id][prop] = value;
}
else if(prop == 'tracks' && !records[id].hasOwnProperty('tracks')) {
  records[id][prop] = [value];
}
else if(prop === 'tracks' && value != "") {
  records[id][prop].push(value);
}
if(value == "") {
  delete records[id][prop];
}
return records;
}

updateRecords(recordCollection, 5439, 'artist', 'ABBA');
  **Your browser information:**

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.84 Safari/537.36 OPR/85.0.4341.75

Challenge: Record Collection

Link to the challenge:

I think I just realised it, is it failing when prop is actually a string with a space?

There is a difference - in the first version, it is accessing the properties that have their names stored in those variables. In the latter, it is looking for those exact strings.

const myObj = {
  num: 42,
}

const prop = 'num'

console.log(myObj[prop])
// 42

console.log(myObj.prop)
// undefined, because there is no property named 'prop'

We use bracket notation in two cases:

  1. The property name is stored in a variable (like here).
  2. The property name is not a valid JS identifier (e.g., has a space, starts with a number, has a hyphen, etc.)
1 Like

Examples of the second situation:

const otherObj = {
  'some property': 'some value',
  '123asdf': 'xyz',
  'fav-food': 'pizza'
}

console.log(otherObj['some property'])
// some value

console.log(otherObj['123asdf'])
// xyz

console.log(otherObj['fav-food'])
// pizza

console.log(otherObj.fav-food)
// throws a JS error

For each of these, we need to use bracket notation because the prop names are not valid JS identifies. Note that when we defined them in the object, we had to use quotes, for the same reason. There is nothing wrong with that - there may be cases where you want to do this or where data is passed to you like this - it just takes a little extra work.

1 Like

Thank it is much clearer now!