0

I was trying out different objects and I noticed a little strange behavior in Javascript JSON objects. Would be great if someone can elaborate.

Example:

var bat={ 3:"FA", 7:"WER", 1:"JWRT",d:"EWR",a:"bA",8:"ADB"};

For this Json object, when it has integers as keys (works even if you enclose the integers in double quotes), and when you try to get the keys using Object.keys() or by simply printing bat the following order is seen.

{1: "JWRT", 3: "FA", 7: "WER", 8: "ADB", d: "EWR", a: "bA"}

The ordering does not happen automatically for Json Objects when the keys are strings (even if it is a Json Object containing string keys exclusively, or has integer and string keys interspersed).

In the case where there are string and integer keys in the same Json Object the integers get to the beginning of the array of keys.

Is there some reason for this behavior? Thanks in advance...

Shruti Saagar
  • 79
  • 1
  • 11
  • 1
    This isn't JSON, keys in JSON must be strings. Everywhere you use "JSON object", you should actually write just "object". – RemcoGerlich Mar 16 '18 at 13:56
  • Object's keys don't follow any order. Why? because it doesn't make sense. If you need to loop over those keys, use the function `Object.keys` and then execute the function `sort`. – Ele Mar 16 '18 at 13:56
  • https://stackoverflow.com/questions/5525795/does-javascript-guarantee-object-property-order – epascarello Mar 16 '18 at 13:57

1 Answers1

1

The order of object keys is never guaranteed. Even when you use numeric keys, they are internally strings.

From the ECMA Specification:

4.3.3 Object

An object is a member of the type Object. It is an unordered collection of properties each of which contains a primitive value, object, or function. A function stored in a property of an object is called a method.

Community
  • 1
  • 1
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
  • Mark as duplicated! `:)` – Ele Mar 16 '18 at 13:58
  • Yes correct, thats what I am trying to understand. So those numbers are strings internally, then came the question as to how they are ordering just "integer strings" alone. Any idea? – Shruti Saagar Mar 16 '18 at 13:58
  • As I stated, there is no guarantee of any particular order, the order you get, may not be the order I get. It is implementation specific. Trying to reason out why the order is what it is is pointless. If the order matters to you, try a Map. – Scott Marcus Mar 16 '18 at 14:00