Creates an object from an array, using the specified key and excluding it from each value.
Array.prototype.reduce()
to create an object from arr
.key
and the associated data
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' } }
JavaScript, Array
Creates an object from an array, using a function to map each value to a key.
JavaScript, Array
Filters an array of objects based on a condition while also filtering out unspecified keys.
JavaScript, Array
Creates an array of elements, grouped based on the position in the original arrays and using a function to specify how grouped values should be combined.