(Updates in ECMAScript 2015 ("ES6"): Please refer to the latest information at the end of this response.)
The concept of object properties having no specific order applies to both JavaScript and JSON. If you require order, utilizing an array instead of object properties is necessary. To establish order, you should modify your structure to include children: []
as opposed to child: {}
. Subsequently, inserting a new entry between two elements can be accomplished by employing the splice
function (specification | MDN).
Regarding the ordering of object properties:
JSON
As stated on the JSON website:
An object consists of an unordered collection of name/value pairs.
(My personal emphasis)
JavaScript
In JavaScript, there are no specifications governing the sequence in which properties are accessed during a for-in
loop—refer to §12.6.4 of the specification:
The process and sequence for enumerating properties (step 6.a in the initial algorithm, step 7.a in the subsequent one) remain unspecified.
(My personal emphasis)
Consequently, each JavaScript engine has the liberty to determine its behavior. It is possible that they access properties based on when they were added to the object (as seen in numerous engines), alphabetically, or depending on what is most convenient for their property storage mechanism, potentially a hash tree resulting in seemingly random ordering if the hashing method is unknown.
Similarly, Object.keys
does not provide any promised order; the only assurance given in the specification is that if an engine commits to an order for for-in
, then Object.keys
must adhere to that same order. Yet, since the specification does not necessitate engines to guarantee an order...
With the introduction of ECMAScript 2015 (ES6), object properties now possess an order:
- Introduce keys as a fresh empty List.
- For every individual property key P belonging to O that represents an integer index, arrange them numerically in ascending order
- Add P as the final element of keys.
- For all property keys P of O representing strings but not being an integer index, maintain the order of creation while listing them
- Append P as the last item in keys.
- For each property key P of O representing a Symbol, follow the order of creation
- Include P as the ultimate element in keys.
- Deliver keys.
...therefore, by manipulating the sequence of property additions to the object, achieving this becomes viable. Although I do not propose implementing it, this option is now feasible on compliant engines.