Convert an array to an object keyed by id in JavaScript
Intermediate · 3 min read
Data often arrives as a list of records, each with an id. To find one record you would have to search the whole list every time. A lookup is the same data stored by id, so users[2] takes you straight to user 2. Shopping carts, caches and anything that joins two lists together use this pattern.
In this tutorial you will turn a list into a lookup with reduce, then with Object.fromEntries, then with a Map. You will also break the reduce version on purpose by forgetting one line, and learn to recognize the error it gives. You should know objects, arrow functions and the basics of reduce.
Setting a property by name
Square brackets let you set a property whose name is in a variable. If the name is a number, it is turned into a string, because every key of a plain object is a string.
const lookup = {};
lookup[2] = 'Bola';
console.log(lookup); // { '2': 'Bola' }
console.log(Object.keys(lookup)); // [ '2' ]
console.log(lookup['2'] === lookup[2]); // true
Reading with lookup[2] still works, because the 2 is turned into '2' for reading too.
Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.
32 Reduce a list into an object
fairTurn a list of records into a lookup keyed by id. Then find out what happens if you forget to return the accumulator.
Stuck? Three hints, smallest first
- 1. The accumulator is the object you are building, and you must return it every time.
- 2. An object key is always a string, so a numeric id comes back as
‘1’. - 3.
Object.fromEntries(rows.map(...))does the same job without an accumulator to forget.
Step 1: build the object with reduce
The accumulator is the object you are building. Start with {}. For each row, add it under its id, then hand the object on to the next step.
const rows = [
{ id: 1, name: 'Ada' },
{ id: 2, name: 'Bola' },
{ id: 3, name: 'Chi' },
];
const indexById = (list) => list.reduce((acc, row) => {
acc[row.id] = row;
return acc;
}, {});
const keyed = indexById(rows);
console.log(keyed[2].name); // Bola
console.log(Object.keys(keyed)); // [ '1', '2', '3' ]
console.log(keyed[1] === rows[0]); // true
keyed[2] goes straight to Bola. The keys are strings, even though the ids were numbers. And the values are the original row objects, not copies.
Step 2: forget the return
Here is the classic reduce bug. Remove return acc;:
const rows = [
{ id: 1, name: 'Ada' },
{ id: 2, name: 'Bola' },
];
try {
rows.reduce((acc, row) => { acc[row.id] = row; }, {});
} catch (e) {
console.log(e.constructor.name); // TypeError
console.log(e.message); // Cannot set properties of undefined (setting '2')
}
Follow it one step at a time. The first call gets {}, sets acc[1], and then returns nothing, which in JavaScript means undefined. The second call gets undefined as acc and tries to set acc[2] on it. That is what fails.
The error points at the second row, but the mistake is the missing return. If you ever see "cannot set properties of undefined" inside a reduce, check the return first. The message above is node's wording; browsers may word it differently.
Step 3: no accumulator to forget
Object.fromEntries builds an object from a list of [key, value] pairs. map can make those pairs.
const rows = [
{ id: 1, name: 'Ada' },
{ id: 2, name: 'Bola' },
{ id: 3, name: 'Chi' },
];
const viaEntries = Object.fromEntries(rows.map((r) => [r.id, r]));
console.log(Object.keys(viaEntries)); // [ '1', '2', '3' ]
console.log(viaEntries[3].name); // Chi
Same object, and there is no accumulator, so there is no return to forget. Many people find this version easier to read.
Step 4: a Map keeps the numbers
A Map is a built-in collection of key and value pairs. Unlike an object, its keys can be any value, so a number stays a number.
const rows = [
{ id: 1, name: 'Ada' },
{ id: 2, name: 'Bola' },
{ id: 3, name: 'Chi' },
];
const asMap = new Map(rows.map((r) => [r.id, r]));
console.log(asMap.get(2).name); // Bola
console.log([...asMap.keys()]); // [ 1, 2, 3 ]
console.log(asMap.size); // 3
You read with get and add with set instead of square brackets. A Map also knows its own size. This matters when you might have both the id 1 and the id '1': an object would mix them up, a Map keeps them apart.
Step 5: two records with the same id
const rows = [
{ id: 1, name: 'Ada' },
{ id: 2, name: 'Bola' },
];
const indexById = (list) => list.reduce((acc, row) => {
acc[row.id] = row;
return acc;
}, {});
const keyed = indexById([...rows, { id: 1, name: 'Late' }]);
console.log(Object.keys(keyed)); // [ '1', '2' ]
console.log(keyed[1].name); // Late
A key can only hold one value, so the later record replaces the earlier one. No error, no warning. If duplicate ids would be a bug in your data, check for them before building the lookup.
The full solution
The panel builds the same lookup three ways, shows the string keys, and runs the reduce with its return removed. Press Run and read the line that names the error.
const rows = [
{ id: 1, name: 'Ada' },
{ id: 2, name: 'Bola' },
{ id: 3, name: 'Chi' },
];
const indexById = (list) => list.reduce((acc, row) => {
acc[row.id] = row;
return acc; // forget this line and the next call gets undefined
}, {});
const viaEntries = Object.fromEntries(rows.map((r) => [r.id, r]));
const asMap = new Map(rows.map((r) => [r.id, r]));
const forgotten = (() => {
try {
return rows.reduce((acc, row) => { acc[row.id] = row; }, {});
} catch (e) { return e.constructor.name; }
})();
const keyed = indexById(rows);
console.log('lookup by id :', keyed[2].name);
console.log('the keys :', Object.keys(keyed), '<- strings, though the ids were numbers');
console.log('via fromEntries:', Object.keys(viaEntries));
console.log('a Map instead :', asMap.get(2).name, ' size', asMap.size);
console.log('forgetting the return:', forgotten);
console.log('a duplicate id overwrites:', Object.keys(indexById([...rows, { id: 1, name: 'Late' }])));
Output
9 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 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('every record is reachable by its id', keyed[2].name, 'Bola');
test('the keys became strings', Object.keys(keyed), ['1', '2', '3']);
test('a numeric lookup still works, because it is converted too', keyed['2'] === keyed[2], true);
test('the values are the original objects', keyed[1] === rows[0], true);
test('Object.fromEntries gives the same thing', same(viaEntries, keyed), true);
test('forgetting to return the accumulator throws', forgotten, 'TypeError');
test('a duplicate key keeps the last record', indexById([...rows, { id: 1, name: 'Late' }])[1].name, 'Late');
test('a Map keeps numeric keys as numbers', [...asMap.keys()], [1, 2, 3]);
test('and it reports its size directly', asMap.size, 3);
The forgotten return is the classic reduce bug, and the error it produces is one step removed from the cause: the first call succeeds and returns undefined, and the second call then fails trying to set a property on it. If you see "cannot set properties of undefined" inside a reduce, this is why.
Object.fromEntries avoids the whole shape, and a Map avoids the other problem in the assertions: object keys are strings, so a lookup keyed by numeric id quietly converts 1 to '1'. Harmless until you have ids of 1 and '1', or you iterate and find your integer keys reordered.
Common mistakes
- Forgetting
return acc. The next step getsundefinedand throws. Every path through the callback must return the accumulator. - Expecting number keys. Object keys are strings, so
Object.keysgives'1', not1. Use aMapwhen the type matters. - Not noticing duplicates. A repeated id silently overwrites the earlier record.
Try it yourself
- Build a lookup of
rowskeyed bynameinstead ofid. - Build a lookup from id to name only, so
lookup[2]is'Bola'. - Write
indexByIdso it throws an error when it meets an id it has already seen.