Array to object based on key

JavaScript, Array, Object · Jun 27, 2021

Creates an object from an array, using the specified key and excluding it from each value.

  • Use Array.prototype.reduce() to create an object from arr.
  • Use object destructuring to get the value of the given 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' } }

Written by Angelos Chalaris

I'm Angelos Chalaris, a JavaScript software engineer, based in Athens, Greece. The best snippets from my coding adventures are published here to help others learn to code.

If you want to keep in touch, follow me on GitHub or Twitter.

More like this