I have been following a JavaScript course (freeCodeCamp) on Youtube Timestamp:02:03:06. Before following up with their solution I made my own attempt. In the project, I am supposed to create a function updateRecords that adds information to the records of a "collection" object following this criteria:
- If property to be added to record is an empty string value, delete the property
- If it already has a value, update the old value to new value.
- If the update property is a track/song, add that to the track list.
I am getting this error:
Uncaught TypeError: Cannot read properties of undefined (reading 'hasOwnProperty')
at updateRecords (updateFunction.js:33:23)
at updateFunction.js:52:13
Here's my initial attempt:
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"
}
};
var collectionCopy = JSON.parse(JSON.stringify(collection));
function updateRecords(id, prop, value) {
//update property for existing record
//add track to record
if (prop === "tracks") {
if (collection.id.hasOwnProperty("tracks")){
collection.id.tracks.push(value);
} else {
collection.id.tracks = [value];
}
} else {
if (collection.hasOwnProperty(id)) {
//update the record property only if the record update property isn't an empty string
if (value !== undefined) {
collection.id[prop] = value;
} else {
delete collection.id.prop;
}
}
}
return collection;
}
console.log(updateRecords("5439", "tracks", "Take a chance on me"))