-1

I am currently doing FreeCodeCamp and encounter this trouble. When I pass an argument to a function, the name of the parameter literally turns into the property of an object.

Here is my code:

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) {

  //first requirement
  if(prop === "tracks" && collection[id].   
    hasOwnProperty("tracks") === false) {
      collection[id].tracks = [];
    }

  //second requirement
  if(prop !== "tracks" && value !== ""){
    collection[id].prop = value;
  }
  
  return collection;
}

and When I passed updateRecords(5439, "artist", "ABBA") to the function, I got

5439:{
 album: "ABBA Gold"
 prop : "ABBA"
}

instead of

5439:{
 album: "ABBA Gold"
 artist: "ABBA"
}

The name of the arguments literally turned into the property of the object, how do I fix this? Thank you

Mattmmmmm
  • 155
  • 1
  • 6
  • You want `whatever[prop]` instead of `whatever.prop`. The first uses the value of the variable named `prop`; the second uses the string `"prop"`. I'll try to find a decent duplicate target. (For comparison, you already use this technique in your code via `[id]`.) – apsillers Jun 25 '20 at 16:06
  • Like https://stackoverflow.com/q/4255472/438992 or several others. – Dave Newton Jun 25 '20 at 16:07

1 Answers1

0

Just use if (key in obj) and then set obj[id][key] = val:

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, key, val) {
  if (id in collection)
    collection[id][key] = val;
}

updateRecords(5439, "artist", "ABBA");
console.log(collection);
Lewis
  • 4,285
  • 1
  • 23
  • 36