Tell us what’s happening:
I’m trying to solve the records- javascript challenge.
Acccording to given conditions I’ve added the following code
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" && value != "") {
collection[id].prop = value ;
} else if(prop == "tracks" && !collection[id].hasOwnProperty("tracks")) {
collection[id].prop = [];
} else if (prop == tracks && value != "") {
collection[id].prop.push(value);
}
return collection;
}
// Alter values below to test your code
updateRecords(5439, "artist", "ABBA");
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:61.0) Gecko/20100101 Firefox/61.0.
Link to the challenge:
Question to point you in the right direction: Is ‘collection’ (currently as it is) editable as an object? Does any parsing need to take place?
And does ‘collectionCopy’ do that parsing for you already?
Here is the solution. SPOILER ALERT!!!
// 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) {
// Conditionals
if (prop !== "tracks" && value !== "") {
collectionCopy[id][prop] = value;
} else if (prop === "tracks" && !collectionCopy[id].tracks) {
collectionCopy[id][prop] = [ value ];
} else if (prop === "tracks" && value !== "") {
collectionCopy[id].tracks.push(value);
} else if (value === "") {
delete collectionCopy[id][prop];
}
// Set 'collection' equal to your changes.
collection = collectionCopy;
return collection;
}
// Alter values below to test your code
updateRecords(5439, "artist", "ABBA");
else if(prop == "tracks" && !collection[id].hasOwnProperty("tracks")) {
collection[id].prop = [];
Hint: This line reads –
- If the prop equals ‘tracks’
- and the collection[id] doesn’t have a prop named ‘tracks’
- set collection[id].tracks to an empty array.