1

I have an object that varies in values and order of keys.

var obj = { extension50: {}, extension55: {}, main: {} }

Note I have "main" key placed out of order. It should be placed in the beginning so when someone iterates through keys of this object it would come up first.

What's the best way of achieving it?

Anonymous
  • 4,225
  • 6
  • 53
  • 86
  • There is not guarantee that the order stays the same. [Related Question](http://stackoverflow.com/questions/5525795/does-javascript-guarantee-object-property-order) – sirlunchalot May 21 '17 at 15:13
  • As mentioned, objects are unordered and there is no way to guarantee order. Possibly do something like: `var obj = [ {}, { extension50: {}, extension55: {} }]` where the first index of the array is guaranteed to hold values of what you'd normally have in `main` – philip yoo May 21 '17 at 15:17
  • It depends on which version of ECMAScript you are working on. With respect to ECMAScript 2015 you can use [Map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) which maintains insertion order as you are looking for – meteorzero May 21 '17 at 15:22
  • 1
    @philipyoo: That's outdated information. See the first of the duplicates above. – T.J. Crowder May 21 '17 at 15:26

1 Answers1

1

JavaScript objects are not ordered. If you want a specific order, use arrays.

Hubert Grzeskowiak
  • 10,887
  • 4
  • 47
  • 61