Tell us what’s happening:
Ok, I’m stumped. I’ve searched this forum and google. I’ve read the replies and I still don’t understand why my code isn’t working on this exercise.
The only test I fail is the second one, " After updateRecords(5439, “tracks”, “Take a Chance on Me”),tracksshould have"Take a Chance on Me"` as the last element."
So the problem MUST be in the code that attempts to create the “tracks” property when it doesn’t exist. But despite knowing that, I cannot figure out how to fix it.
Any assistance would be greatly appreciated.
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"
}
};
// Keep a copy of the collection for tests
var collectionCopy = JSON.parse(JSON.stringify(collection));
// Only change code below this line
function updateRecords(id, prop, value) {
if (prop == "tracks" && !(collection[id].hasOwnProperty(prop))) {
collection[id].tracks = [];
collection[id][prop] = value;
} else if (prop === "tracks" && value !== "") {
collection[id][prop].push(value);
} else if (prop !== "tracks" && value !== "") {
collection[id][prop] = (value);
} else if (value == "") {
delete collection[id][prop];
}
return collection;
}
// Alter values below to test your code
updateRecords(5439, "artist", "ABBA");
Your browser information:
User Agent is: Mozilla/5.0 (X11; Linux x86_64; rv:68.0) Gecko/20100101 Firefox/68.0.
When your solution is run with updateRecords(5439, “tracks”, “Take a Chance on Me”), the tracks value is not an array. Can you see where your solution is assigning a string instead of an array?
I think I was confused by the instructions, which state " If prop is "tracks" but the album doesn’t have a "tracks" property, create an empty array before adding the new value to the album’s corresponding property."
Apparently, you’re not supposed to do that at all - in fact, it messes you up if you do it!
/* if the record doesn't have a tracks property... */
collection[id].tracks = [];
/* and then in EITHER case... */
collection[id].tracks.push(value);
But the collection[id].tracks = [value]; is a shorthand way of creating an array AND inserting that first value, in a single line. Be aware of both ways, but don’t feel bound to one or the other.