Creates an object from an array, using a function to map each value to a key.
- Use
Array.prototype.reduce()
to create an object fromarr
. - Apply
fn
to each value ofarr
to produce a key and add the key-value pair to the object.
代码实现
const indexBy = (arr, fn) =>
arr.reduce((obj, v, i) => {
obj[fn(v, i, arr)] = v;
return obj;
}, {});
indexBy([
{ id: 10, name: 'apple' },
{ id: 20, name: 'orange' }
], x => x.id);
// { '10': { id: 10, name: 'apple' }, '20': { id: 20, name: 'orange' } }
翻译自:https://www.30secondsofcode.org/js/s/function-based-array-indexing