I'm new to Javascript, so this is probably fairly easy.
I have this JSON:
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"
}
};
And this function:
// Keep a copy of the collection for tests
var collectionCopy = JSON.parse(JSON.stringify(collection));
function updateRecords(id, prop, value) {
if (value !== "" && prop !== "tracks"){
return collection.id.prop.value;
} else if (value !== "" && prop === "tracks"){
return collection.id.prop.push(value);
} else {
delete collection.id.prop.value;
}
return collection;
}
These are my tests:
updateRecords(5439, "artist", "ABBA");
updateRecords(2548, "artist", "");
updateRecords(1245, "tracks", "addicted to love");
updateRecords(2458, "tracks", "");
What I need to do is write a function that will access the JSON
information and add the information if the argument value
is non-blank (value !== ""
) and prop
argument is not tracks
(props !== "tracks
) update or set the value for the argument prop
.
Furthermore if the argument prop
is tracks (props === "tracks"
) and the argument value
is also non-blank (value !== ""
) I need to push the value onto the end of the tracks
inside of the JSON
file.
My question is how could I go about doing this? Mine is obviously failing I understand that I need to delete
and push
the information, but accessing the correct data is confusing to me, would I do something like: return collection.id.prop.push(value);
?