JavaScriptFundamental (ES6), part 1
Object key order in JavaScript
35 The order object keys come back in
hardBuild an object with a mix of integer-like and ordinary string keys and report the order Object.keys gives them. Then find where the boundary of "integer-like" is, and what deleting and re-adding a key does to its position.
Stuck? Three hints, smallest first
- 1. Keys that look like array indexes come first, sorted numerically. Everything else follows in insertion order.
- 2. An array index is a non-negative integer below 2³²−¹. So
'-1','1.5'and'4294967295'are ordinary strings. - 3. A
Maphas none of these rules: insertion order, whatever the key type.
const mixed = { b: 1, 2: 'two', a: 3, 1: 'one', '-1': 'minus', '1.5': 'float', 10: 'ten' };
const edge = { '4294967294': 'last index', '4294967295': 'one past it', '0': 'first' };
const strings = { a: 1, b: 2 };
delete strings.a;
strings.a = 3; // re-added, so it goes to the end
const integers = { 1: 'x', 2: 'y' };
delete integers[1];
integers[1] = 'z'; // re-added, back to its numeric slot
const asMap = new Map([['b', 1], [2, 'two'], ['a', 3]]);
console.log('mixed keys :', Object.keys(mixed));
console.log('as JSON :', JSON.stringify(mixed));
console.log('index limit :', Object.keys(edge));
console.log('string re-add :', Object.keys(strings));
console.log('integer re-add:', Object.keys(integers));
console.log('a Map :', [...asMap.keys()]);
Output
8 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 8 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('integer-like keys come first, in ascending numeric order', Object.keys(mixed), ['1', '2', '10', 'b', 'a', '-1', '1.5']);
test('JSON.stringify follows the same order', JSON.stringify(mixed), '{"1":"one","2":"two","10":"ten","b":1,"a":3,"-1":"minus","1.5":"float"}');
test('a spread copy inherits the ordering rules, not the source order', Object.keys({ ...mixed }), ['1', '2', '10', 'b', 'a', '-1', '1.5']);
test('the largest array index sorts as a number', Object.keys(edge).slice(0, 2), ['0', '4294967294']);
test('one above it is an ordinary string key, so it lands after them', Object.keys(edge)[2], '4294967295');
test('deleting and re-adding a string key moves it to the end', Object.keys(strings), ['b', 'a']);
test('but an integer-like key returns to its numeric position', Object.keys(integers), ['1', '2']);
test('a Map keeps insertion order whatever the key type', [...asMap.keys()], ['b', 2, 'a']);
Key order is specified, not arbitrary, and it is not insertion order. Integer-like keys are sorted numerically and hoisted in front of everything else, then string keys follow in insertion order, then symbols. So an object keyed by numeric id will iterate in id order whether you wanted that or not, and an object keyed by '2024-01' style strings will iterate in the order you inserted them.
This is a real trap for anything ordered by user intent — a form's fields, a column layout, a sequence of steps. If order is part of the data, use an array of pairs or a Map. Note that the reordering survives a spread: { ...obj } re-inserts every key and gets the same rules applied again.