Skip to content

Instantly share code, notes, and snippets.

@jgresalfi
Created September 4, 2016 20:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jgresalfi/1588ece26618998d77b9a8eb990c7132 to your computer and use it in GitHub Desktop.
Save jgresalfi/1588ece26618998d77b9a8eb990c7132 to your computer and use it in GitHub Desktop.
Modifying objects/checking properties - record collection example
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) {
var isTracks = collection[id].hasOwnProperty("tracks"),
newArray = [];
if (prop === "album" || prop === "artist") {
collection[id][prop] = value;
} else if (prop === "tracks" && isTracks) {
collection[id][prop].push(value);
} else if (isTracks !== false) {
collection[id][prop] = newArray;
collection[id][prop].push(value);
}
return collection;
}
updateRecords(5439, "tracks", "ABBA");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment