Miha Šušteršič Miha Šušteršič - 4 months ago 8
Javascript Question

changing JSON object values with javascript function inputs

I am completing a freeCodeCamp exercise and I've hit a dead end.

The purpose of the exercise is to write a function that takes 3 arguments (

id, prop, value
).

After some evaluation (check if prop is not blank, check if prop is "tracks"), the function should change the JSON object predefined (a record collection).

Running my code, I get some curious results. The wrong JSON properties get updated, or they do not get updated at all. I suspect that the problem is with the object calling, but I can't figure out what I did wrong. Any help is appreciated.

// 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 update(id, prop, value) {
if(value !== "") {
if(prop == "tracks") {
collection[id][prop].push(value);
}
else {
collection[id][prop] = "";
}
collection[id][prop] = value;
}

return collection;
}

// Alter values below to test your code
update(5439, "artist", "ABBA");


I've also created a codepen with the same code if anyone wants to tinker.

Answer

You want something like

function update(id, prop, value) {
  if(value !== "") {
    collection[id] = collection[id] || {}; // to create id if required
    if(prop == "tracks") {
      collection[id].tracks = collection[id].tracks || []; // create empty tracks array if required
      collection[id].tracks.push(prop);
    }
    else {
      collection[id][prop] = value;
    }
  }

  return collection;
}

The above allows you to create a new id, and it handles adding the FIRST track properly