0

Please point me to an answer if this has been answered before, but I could not find one regarding statically created objects.

const foo = { 
  c: 'c', 
  b: 'b', 
  a: 'a' 
};

Is the order of the keys guaranteed to stay the same when using enumeration like Object.keys()?

user1164937
  • 1,509
  • 2
  • 15
  • 27
  • From mdn: Object.keys() returns an array whose elements are strings corresponding to the enumerable properties found directly upon object. The ordering of the properties is the same as that given by looping over the properties of the object manually. – Mike Cheel Oct 30 '18 at 19:00
  • If the order of properties is important to you, you might want to use an array instead or an array which defines the order (`{ "a": "a", "b": "b", "c": "c", order: ["c", "a", "b"] }`) for a browser/engine independent solution. – Andreas Oct 30 '18 at 19:04

2 Answers2

0

Objects do not preserve order -

An ECMAScript object is an unordered collection of properties each with zero or more attributes that determine how each property can be used—

Use an array if you need order.

Badi8beach
  • 476
  • 1
  • 4
  • 15
  • 1
    That's not true anymore -> [Does ES6 introduce a well-defined order of enumeration for object properties?](https://stackoverflow.com/questions/30076219/does-es6-introduce-a-well-defined-order-of-enumeration-for-object-properties) – Andreas Oct 30 '18 at 19:10
  • 1
    To clarify the above comment, some operations like `Object.getOwnPropertyNames`, `Object.getOwnPropertySymbols` and `Reflect.ownKeys` do use a creation order for non-numerically-named properties. However, your answer is correct when narrowly considering `for-in` and `Object.keys`, which do not use this order. (You might modify your answer to say, "`Object.keys` and `for-in` loops do not consider property creation order.") – apsillers Oct 30 '18 at 19:16
0

Short answer: No. Traditionally, objects do not guarantee anything about the order.

Now, in practice, many browsers do keep insertion order, and ES2015 does have certain guarantees on the order in certain cases. See e.g. this similar question for some more information.

Nevertheless, I would suggest you solve the issue in a more clear ways by e.g. using a Map, or by manually keeping track of the order using a list.

Berthur
  • 1,317
  • 7
  • 17