1
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?

showkey
  • 482
  • 42
  • 140
  • 295
  • 1
    Read the answers here: http://stackoverflow.com/questions/4968406/javascript-property-access-dot-notation-vs-brackets – epascarello Sep 21 '16 at 12:17

2 Answers2

4

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;
Rayon
  • 36,219
  • 4
  • 49
  • 76
R3tep
  • 12,512
  • 10
  • 48
  • 75
  • why `artist` the value of prop can't be passed into the collection[id].prop,to make it be `collection[id]."artist"` ? – showkey Sep 21 '16 at 12:15
  • @it_is_a_literature: That is exactly what the bracket notation does: Dynamic property names. You are already using it that way for the `id`. Same thing applies to `prop`. – Thilo Sep 21 '16 at 12:16
  • 5
    because how in the world is the parse supposed to know you mean a variable and not the string? That is how dot and bracket notation works. – epascarello Sep 21 '16 at 12:16
0

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");
R3tep
  • 12,512
  • 10
  • 48
  • 75
Chandra Sekar
  • 302
  • 1
  • 13