Hello. I’m having a bit of trouble with the exercise “Record Collection”. Here’s my first attempt at it:
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) {
if(prop == "tracks" && value !== "" ) {
if(collection[id].tracks == undefined) {
var emptyArray = [];
collection[id].tracks = emptyArray;
collection[id].tracks.push(value);
} else collection[id].tracks.push(value);
}
if(prop != "tracks" && value !== "") {
collection[id].prop = "";
} else if(value == "") {
delete collection[id].prop;
}
return collection;
}
console.log(updateRecords("1245", "artist", "Random"));
returned "{ 1245: { artist: 'Robert Palmer', tracks: [], prop: '' }"
, instead of changing the name of the artist. I could work my way out of this and pass the exercise by writing another function, assigning a separate conditional statement to each property, like this:
function updateRecords(id, prop, value) {
if((prop == "tracks" && value !== "") && (collection[id].tracks == undefined)) {
var emptyArray = [];
collection[id].tracks = emptyArray;
collection[id].tracks.push(value);
} else if (prop == "tracks" && value != "" ) {
collection[id].tracks.push(value);
} else if (prop == "tracks" && value == "" ) {
delete collection[id].tracks;
}
if(prop == "artist" && value == "") {
delete collection[id].artist;
} else if (prop == "artist" && value != "") {
collection[id].artist = value;
}
if(prop == "album" && value == "") {
delete collection[id].album
} else if (prop == "album" && value != "") {
collection[id].album = value;
}
return collection;
}
However, I wasn’t happy with this solution because I thought there must’ve been another way to accomplish this without having to write explicit “if” statements for each property—which is kind of overkill, I guess.
Just to test the core idea of my first example (accessing an object’s property inside a conditional statement), I thought of writing a simple function that would delete a property if the “value” parameter were empty:
function updateRecords2(id, prop, value) {
if(value == "") {
delete collection[id].prop;
}
return collection; }
But it still didn’t work. So I’m wondering if there’s some way to do what I want?
Thank you.