Yeats
Yeats

Reputation: 2065

How to force an object key-value pair to sit first in an object?

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?

Upvotes: 0

Views: 55

Answers (2)

Madara's Ghost
Madara's Ghost

Reputation: 174987

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.

Upvotes: 3

madox2
madox2

Reputation: 51881

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);

Upvotes: 1

Related Questions