0

I already have an object with something in it:

{
    name: 'Smith',
    age: 24
}

And I want to add something else to it, but force it to sit first. How do I do that?

Yeats
  • 1,950
  • 3
  • 21
  • 43
  • 1
    objects have no order, actually. – Nina Scholz Mar 14 '16 at 21:50
  • I smell an XY problem here. Why do you care about the order of your object's keys? – Madara's Ghost Mar 14 '16 at 21:55
  • @MadaraUchiha Using Meteor and MongoDB to sort fields, and it uses the first key-value pair with a higher priority in that sort. It clearly has order, but maybe that's because Meteor is turning it into JSON behind the scene or something. – Yeats Mar 14 '16 at 21:57
  • If you want to preserve order you should use an array; with ES6 you can be sure that entry orders will be preserved but I think you should find a more elegant solution. – teaflavored Mar 14 '16 at 21:58

2 Answers2

3

In past versions of ECMAScript, the order of keys in an object was undefined (meaning, the order didn't matter, and you couldn't count on the order remaining the same).

In ECMAScript 2015, however, the order was explicitly defined to be the order in which they are inserted, meaning, you can only insert new keys at the end of the object.


According to this answer, it's worth noting that while the order is defined in ES2015, all of the functions from ES5 and below are not required to implement it, for legacy reasons.

However, (speaking from personal experience here, I might be totally wrong) all browsers as far back as I can remember, implemented object order as it is in the specs today.

Community
  • 1
  • 1
Madara's Ghost
  • 158,961
  • 49
  • 244
  • 292
1

In addition to @MadaraUchiha answer, you can create new object with Object.assign() and assign new key first and then the rest:

var obj = {
    name: 'Smith',
    age: 24
};

var obj = Object.assign({}, {prop: 'something else'}, obj);
madox2
  • 39,489
  • 13
  • 88
  • 91