Create Objects from Arrays

This function lets you create an object made up of an array of objects with an 'id' key and any number of additional properties.

js
1const indexOn = (array, key) =>
2 array.reduce((object, value) => {
3 const { [key]: id, ...data } = value;
4 object[id] = data;
5
6 return object;
7 }, {});
8
9// Usage
10indexOn(
11 [
12 { id: 1, name: 'John', age: 30 },
13 { id: 2, name: 'Mary', age: 25 },
14 ],
15 'id',
16);
17
18// [ { id: 1, name: 'John', age: 30 }, { id: 2, name: 'Mary', age: 25 } ]