Given an object definition:
var o = {x :1, y:2, z: 3, b: 4, a: 5, m: 6, X: 7};
At enumeration time, Chrome appears to respect the order in which the attributes are defined:
for (var i in o) { console.log(i, o[i]); }
Yields:
x 1
y 2
z 3
b 4
a 5
m 6
X 7
Does JavaScript and/or the JSON specify this level of order-preservation?
In either case, is it reliable?
No, Javascript specs explicitly do not require any particular enumeration order, they are by definition unordered.
See section 12.6.4 of the ECMAScript specification:
The mechanics and order of enumerating the properties ... is not specified.
There is no guarantee that the properties will appear in the order that they are defined.
Some browsers will retain the properties in the order that they are defined, others wont.
A JSON parser that parses the JSON into something other than a Javascript object could retain the order from the source, otherwise it's not possible to guarantee it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With