user4947695
user4947695

Reputation: 13

How to make `Object.keys` respect the order in which keys are 'declared' in an object?

Given the object:

var opts = {
    'all': 'All',
    0: 'Some option',
    1: 'Cookies',
};

Object.keys(opts) returns this:

["0", "1", "all"]

When I'm expecting this:

["all", "0", "1"] // The order in which the keys are 'declared' in the obj

How can I iterate through the properties in the order in which they appear in the object?

Thanks.

Upvotes: 1

Views: 501

Answers (2)

Lusan Das
Lusan Das

Reputation: 143

No, properties order in objects are not guaranted in JavaScript, you need to use an Array.

Does JavaScript Guarantee Object Property Order?

Upvotes: 0

Alexey Lebedev
Alexey Lebedev

Reputation: 12197

ECMA-262, section 12.6.4 about the for-in statement:

The mechanics and order of enumerating the properties (step 6.a in the first algorithm, step 7.a in the second) is not specified.

You could use array instead:

var opts = [
    {key: 'all', value: 'All'},
    {key: 0,     value: 'Some option'},
    {key: 1,     value: 'Cookies'}
];

Or, in ES6, the Map object:

var opts = new Map([
    ['all', 'All'],
    [0,     'Some option'],
    [1,     'Cookies']
]);

opts.forEach(function(val, key) {
    console.log(key, val);
});

In which case forEach will always iterate key-value pairs in insertion order.

Upvotes: 2

Related Questions