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

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

Anand Sharma
  • 39
  • 1
  • 4

1 Answers1

0

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}
};
HelpingHand
  • 1,045
  • 11
  • 26
  • Name one Javascript implementation that doesn't retain order. – John Jul 18 '18 at 08:56
  • Objects retain order, however using the order of the object elements is not a good idea because they're not an order-based form of data storage. Arrays on the other hand are formed on order, using the element's position within the array as the key. – HelpingHand Jul 18 '18 at 15:03
  • @John I clarified my answer. Of course objects retain order, but you *shouldn't* use that order for data manipulation. – HelpingHand Jul 25 '18 at 18:54