You cannot rely on the output you've said you want using a for-in
loop. Although object properties have order as of ES2015, for-in
loops don't. (Neither does the array from Object.keys
.)
If you want order, you want an array. (But you can use a Map
, too, in some situations; see below.)
Moreover, even with ES2015's property order, the keys you've shown will never be in the order you've shown, because '00'
is different from '11'
, '22'
, and '33'
: It's not a canonical number String. The ES2015 order (for the operations that support it) is properties whose names are strings in canonical number String format, in order numerically, followed by other string-named properties in the order they were added, followed by Symbol-named properties.
So your object will never behave as you've said you want. Use an array.
(Of course, if you introduce a prefix so none of them is in canonical number String format and add the properties in the order you want them, that would work with Object.getOwnPropertyNames
and other operations that support the order. But I really wouldn't do that.)
Another option is to use a Map
, which unlike objects always follows the order that the keys were first used.¹ If you create a Map
like this:
const map = new Map(simple_arr.map(key => [key, "anything"]));
...then looping through that map will reliably visit the '00'
entry, then the '11'
entry, then the '22'
entry, then the '33'
entry:
const simple_arr = ['00', '11', '22', '33'];
const map = new Map(simple_arr.map(key => [key, "anything"]));
for (const [key, value] of map.entries()) {
console.log(key, value);
}
¹ That's the simple version. The longer version: If you add a key/value to the map and that key is not already in the map, it goes at the end of the list of the map's keys. If you set a new value for that key, it doesn't move in that list. If you remove the key and then add it again later, it goes at the end again.