Search code examples
javascriptobject-literal

How to add a key/value pair to a JavaScript object in perticular position?


var obj = {key1: value1, key3: value3};

How can I insert new key value pairs {key2: value2} in second position of the object?


Solution

  • Objects retain order, but it is not an index based form of data storage (getting the 'n-th' element may work, however the index 'n-th' does not always relate directly to the data).

    You want to use an Array if you wish to retain order, or rather, define an index as a value pair within the object:

    var obj = {
      key1: {index: 1, content: contentValue},
      key3: {index: 2, content: contentValue}
    };