0

Can we get keys of a JSON in the same order it was received?

Object.keys(company).length works, but I need confirmation if it will always work.

{
  "hello":"world",
  "welcome":"back",
  "1":"2"
}

How can we get keys in the same order?

["hello","welcome","1"]
Peter B
  • 22,460
  • 5
  • 32
  • 69
  • From [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys): _The Object.keys() method returns an array of a given object's own property names, **in the same order** as we get with a normal loop_. – Shidersz Jan 05 '19 at 21:39
  • 1
    There is no such global guarantee. Neither JS objects (per ECMAScript specs) nor JSON guarantees key order - insert or otherwise. JSON itself expresses your forbids/excludes ordering assumptions. – user2864740 Jan 05 '19 at 21:44
  • 1
    @Shirersz The flaw in that statement is the incorrect assumption that the “normal loop” has a guaranteed order of key iteration. – user2864740 Jan 05 '19 at 21:46
  • Possible duplicate of [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) – Peter B Jan 05 '19 at 22:15

1 Answers1

1

You might be better off storing your data in a Map to ensure insertion order and entry retrieval.

Check out: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map