I don’t understand how property ‘artist’ was added to ‘5439’ object. Please explain or give a link where I can read explanation.
const collection = {
5439: {
album: 'ABBA Gold',
}
};
function updateRecords(id, prop, value) {
if (prop === 'tracks' && value !== '') {
} else if (value !== '') {
collection[id][prop] = value;
console.log(collection);
}
return collection;
}
updateRecords(5439, 'artist', 'ABBA');
https://jsbin.com/wumiyogore/1/edit?js,console
The object collection
has a key of 5439
(the id). That has a value of {album: 'ABBA Gold'}
.
You are saying collection[id][prop] = value
, so collection[5439]['artist'] = 'ABBA'
so assigning the value 'ABBA'
to a key called ‘artist’ on the object with the key 5439 on the object collection
collection = {
5439: {
artist: 'ABBA',
album: 'ABBA Gold'
}
}
collection[5439]['artist']
is ABBA, collection[5439]['album']
is ABBA Gold. If you do
collection[5439]['artist'] = 'The Beatles'
It’ll change artist to the Beatles. If you do
collection[5439]['favouritePet'] = 'Cat'
It’ll add a ‘favouritePet’ property and so on.
I’ve tested this behavior and now I understand that the property will be added automatically if there is none. Thank you.