According to my research, the order of keys in a for..in
loop should be undefined/unreliable – but, if left undisturbed, should be in insertion order – but it's not:
I fetch this data object from the database, ordered by name:
var travel = {
'2': { name: 'bus', price: 10 },
'3': { name: 'foot', price: 0 },
'1': { name: 'taxi', price: 100 }
}
for (way in travel) console.log( travel[way].name ) // => taxi, bus, foot
The keys get ordered numerically (in all of Chrome, Firefox, and Edge). Why?
And (since I was wrong) how can I iterate through them ordered by .name
?
Undefined, yes.
No, you were right the first time: It's undefined. Even in ES2015 (aka "ES6") and above, which do provide property order for some other operations, the older operations
for-in
andObject.keys
are not required to follow the order defined for the new ones.In those other operations (
Object.getOwnPropertyNames
,JSON.serialize
, ...), the order (defined here) isn't purely insertion order: Properties whose names are array indexes according to the spec's definition* come first, in numeric order. Most major JavaScript engines have updated their handling offor-in
to match their handling of these new operations (many already did treat array indexes differently, but they varied in terms of whether they put those before the non-array-indexes or after), but again, it's undefined, and you shouldn't rely on it.If you want pure insertion order, ES2015's
Map
provides that, regardless of the value of the key. Objects don't.Here's an example using
Map
:* The spec's definition of an "array index" is:
In practice, javascript object iterates by keys in insertion order except when keys are numeric. This is probably caused be the need to make array iteration (arrays are objects too) ordered by key.
So, your choices are - respect the standard and use ES6 Map or arrays of objects to guarantee iteration order - make your keys always non-numeric and hope for the best