Creates an object from an array, using the specified key and excluding it from each value.
- Use
Array.prototype.reduce()
to create an object fromarr
. - Use object destructuring to get the value of the given
key
and the associateddata
and add the key-value pair to the object.
代码实现
const indexOn = (arr, key) =>
arr.reduce((obj, v) => {
const { [key]: id, ...data } = v;
obj[id] = data;
return obj;
}, {});
indexOn([
{ id: 10, name: 'apple' },
{ id: 20, name: 'orange' }
], 'id');
// { '10': { name: 'apple' }, '20': { name: 'orange' } }
翻译自:https://www.30secondsofcode.org/js/s/array-to-object-based-on-key