Tell us what’s happening:
I’ve seen some of the solutions, but am trying to do it my way and can’t seem to understand why my code isn’t working.
Missing one of the conditions.
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"
}
};
// 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(prop) == false) {
collection[id][prop] = [value];
}
else if (prop == "tracks" && collection[id].hasOwnProperty(prop) == true) {
collection[id][prop].push(value);
}
else if (value === "") {
delete collection[id][prop];
}
else {
collection[id][prop] = value;
}
return collection;
}
updateRecords(5439, "artist", "ABBA");
Your browser information:
User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36.
You are trying to delete tracks in an else-if, but since the else-if above that one is true (where you push), the line with the deletion is never reached. As soon as one if-statement in this chain is true, all the rest gets ignored …
Some of the answers look much simpler than my multiple else if's.
How could I simplify it and use less code?
Should I use only if's?
What I mean is there a better way to look at this problem and resolve it in a more succinct way? Still working on thinking like a developer.
thank you @ILM.
I had missed the short circuit property and that’s a great thing to know.
So I understood the second part of it.
What is this doing exactly?
collection[id][prop] = collection[id][prop]
comparing with itself? is it a boolean expression?
Not sure how it’s checking if there is a value to prop already in the object.