Created
April 4, 2018 20:40
-
-
Save nickihastings/b31f5e005cc8b65bc4aa0a937962ae7d to your computer and use it in GitHub Desktop.
You are given a JSON object representing a part of your musical album collection. Each album has several properties and a unique id number as its key. Not all albums have complete information. Write a function which takes an album's id (like 2548), a property prop (like "artist" or "tracks"), and a value (like "Addicted to Love") to modify the d…
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 a value is set... | |
if(value !==""){ | |
//first check if the property is not 'tracks'. If it's anything else, update | |
//that entry with the new value. | |
if(prop !== "tracks"){ | |
collection[id][prop] = value; | |
} | |
//otherwise if the property IS 'tracks'... | |
else{ | |
//see if the collection id already has a 'tracks' property. If it does | |
//push the new value to the array. | |
if(collection[id].hasOwnProperty("tracks")){ | |
collection[id][prop].push(value); | |
} | |
//if there is no tracks property create one and add the array. | |
else{ | |
var arr = [value]; | |
collection[id][prop] = arr; | |
} | |
} | |
} //end if there's a value | |
//if there's no value set for the property then delete that property | |
else{ | |
delete collection[id][prop]; | |
} | |
return collection; | |
} | |
// Alter values below to test your code | |
updateRecords(5439, "artist", "ABBA"); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment