Does Object.keys keep your insert order in JavaScript?
Assign the keys b , 2 , a , 1 to a plain object and Object.keys comes back as 1, 2, b, a . That is not a bug and it is not random: the spec splits keys into two groups and sorts one of them. The test const o = { } ; o . b = 1 ; o [ 2 ] = 2 ; o . a = 3 ; o [ 1 ] = 4 ; console . log ( Object . keys ( o ) ) ; // [ '1', '2', 'b', 'a' ] console . log ( JSON . stringify ( o ) ) ; //…
When assigning keys "b", 2, "a", and 1 to a plain JavaScript object, `Object.keys` returns the keys in the order of 1, 2, "b", "a". This behavior is intentional and not a bug; the specification divides keys into two groups and sorts one of them. The integer-like keys "1" and "2" are sorted in ascending numeric order, while the string keys "b" and "a" follow in the order they were inserted.
Integer keys, such as "01", "1.5", and "-1", are excluded from the integer group and remain in the string group. If relying on insertion order is crucial, consider using a Map, as it maintains the insertion order for all key types, including integer-like keys. In the provided examples, a plain object and a Map with the same keys were used to illustrate the difference in key ordering.
Rewritten by urgent.news; may contain errors — check the original.
Source: dev.to