简体   繁体   中英

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM