1

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.

  • 4
    There is no order in objects, so expecting a certain order will always fail – adeneo May 28 '15 at 06:26
  • [Object.keys](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys).. `same order as that provided by a for...in loop` - `The for..in statement iterates over the enumerable properties of an object, in arbitrary order` – Arun P Johny May 28 '15 at 06:27
  • [Spec](http://www.ecma-international.org/ecma-262/5.1/#sec-15.2.3.14) - `If an implementation defines a specific order of enumeration for the for-in statement, that same enumeration order must be used in step 5 of this algorithm.` - order is optional – Arun P Johny May 28 '15 at 06:28
  • Thanks. Yeah, I just realized `for in` goes in the same order (and thanks for the links and explanation). So, is there any way of doing this? Perhaps getting the array and then using `sort`? – user4947695 May 28 '15 at 06:28
  • 3
    You can sort the array, if you want the keys in a certain order, but there is no "original order", as an objects keys aren't ordered. – adeneo May 28 '15 at 06:31
  • Well, by "original order" I mean the order in which I declared them in the object (intuitively, I thought `Object.keys` returned them in that order). I understand that there's no order, and there's also no order to be expected from the array `Object.keys` returns (or the order in which `for ... in` iterates through each key). I'm doing this on node, so perhaps I *could* get away with seeing how the returned array looks like and from there write a `sort`. Thank you. – user4947695 May 28 '15 at 06:36

2 Answers2

2

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.

Alexey Lebedev
  • 11,988
  • 4
  • 39
  • 47
0

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

Does JavaScript Guarantee Object Property Order?

Community
  • 1
  • 1
Lusan Das
  • 133
  • 2
  • 9