Search code examples
javascriptobject-literal

When a key appears repeatedly in an object literal, what is the value that finally ends up in the object?


Try running this code:

var oObject = {
  "COL_SEQ":16,
  "SERVICE_CD":0.000000,
  "SERVICE_ID":0.000000,
  "COL_NAME":"",
  "COL_OPTION":"nosort nofilter",
  "COL_CLASS":"REMOVE_PATIENT",
  "COL_TYPE":"",
  "COL_LABEL":"",
  "COL_OPTION":""
};

console.log(oObject.COL_SEQ);
console.log(oObject.COL_OPTION);
console.log(oObject.COL_CLASS);

I would expect the 2nd message to show "nosort nofilter", but it doesn't; it shows a blank message.

Why is this happening?


Solution

  • You have a second (empty) COL_OPTION at the end of the object, which overwrites your initial one.

    If you take out the second one, your code works fine:

    var oObject = {"COL_SEQ":16,"SERVICE_CD":0.000000,"SERVICE_ID":0.000000,"COL_NAME":"","COL_OPTION":"nosort nofilter","COL_CLASS":"REMOVE_PATIENT","COL_TYPE":"","COL_LABEL":""};