showkey
showkey

Reputation: 348

Why the parameter can't be passed properly when function called?

var collection = {
    "5439": {
      "album": "ABBA Gold"
    }
};
function updateRecords(id, prop, value) {
  if(prop !== "tracks" && value !== ""){
    collection[id].prop=value;
  }
  return collection;
}
updateRecords(5439, "artist", "ABBA");

why the result is Object { album="ABBA Gold", prop="ABBA"},not Object { album="ABBA Gold",artist="ABBA"}?
When to parse collection[id].prop=value; ,the value of prop is artist,the value of id is 5439,so collection[id].prop=value; should parsed into collection[5439].artist="ABBA";,why not?

Upvotes: 1

Views: 70

Answers (2)

Chandra Sekar
Chandra Sekar

Reputation: 312

change the line collection[id].prop=value;

to collection[id][prop]=value;

var collection = {
  "5439": {
    "album": "ABBA Gold"
  }
};

function updateRecords(id, prop, value) {
  if (prop !== "tracks" && value !== "") {
    collection[id][prop] = value;
  }
  return collection;
}
updateRecords(5439, "artist", "ABBA");

Upvotes: 0

R3tep
R3tep

Reputation: 12854

Use Bracket notation

An object property name can be any valid JavaScript string, or anything that can be converted to a string, including the empty string. However, any property name that is not a valid JavaScript identifier (for example, a property name that has a space or a hyphen, or that starts with a number) can only be accessed using the square bracket notation. This notation is also very useful when property names are to be dynamically determined (when the property name is not determined until runtime).

collection[id][prop] = value;

instead of,

collection[id].prop=value;

Upvotes: 4

Related Questions