Tell us what’s happening:
This challenge has cost me several hours of my life and I could really use some help with it.
I came up with a working solution, though I thought I could make it better, and this is where things got frustrating.
I use collection[id].tracks.push(value) in the working solution and things look bright, but in the code below it doesn’t append an element to the “tracks” array, but replaces all its elements.
What am I doing wrong?
Your code so far
// 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"
}
};
function updateRecords(id, prop, value) {
console.log(id, prop, value);
if (value ===""){ // value empty
delete collection[id][prop];
} else {
if (prop !== "tracks"){ // value not empty, prop is not "tracks"
collection[id][prop]=value;
} else { // value not empty and prop is "tracks" !!! ERROR HAPPENS HERE - collection[id].tracks.push(value) resets "tracks" only to the `value` and drops other elements;
if (collection.hasOwnProperty("tracks")) {
collection[id].tracks.push(value);
} else { // value not empty, prop is "tracks" and album has no "tracks"
collection[id].tracks = [];
collection[id].tracks.push(value);
}
}
}
console.log(collection[id]);
return collection;
}
// Alter values below to test your code
updateRecords(5439, "artist", "ABBA");
updateRecords(2468, "tracks", "sample track");
updateRecords(2548, "tracks", "sample track");
my logs are:
{“album”:“ABBA Gold”,“artist”:“ABBA”}
{“album”:“1999”,“artist”:“Prince”,“tracks”:[“sample track”]}
{“album”:“Slippery When Wet”,“artist”:“Bon Jovi”,“tracks”:[“sample track”]}
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.87 Safari/537.36
.
Challenge: Record Collection
Link to the challenge:
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/record-collection