Map an array to an object

JavaScript, Array, Object · Feb 4, 2023

Maps an object array to an object, using the provided mapping functions.

  • Use Array.prototype.reduce() to map the array to an object.
  • Use mapKey to map the keys of the object and mapValue to map the values.
const objectify = (arr, mapKey, mapValue = i => i) =>
  arr.reduce((acc, item) => {
    acc[mapKey(item)] = mapValue(item);
    return acc;
  }, {});
const people = [ { name: 'John', age: 42 }, { name: 'Adam', age: 39 } ];
objectify(people, p => p.name.toLowerCase());
// { john: { name: 'John', age: 42 }, adam: { name: 'Adam', age: 39 } }
objectify(
  people,
  p => p.name.toLowerCase(),
  p => p.age
);
// { john: 42, adam: 39 }

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

  • Map array to object

    Maps the values of an array to an object using a function.

    JavaScript, Array · Oct 21, 2020

  • Map an object to an array

    Maps an object to an object array, using the provided mapping function.

    JavaScript, Object · Feb 5, 2023

  • Index array based on function

    Creates an object from an array, using a function to map each value to a key.

    JavaScript, Array · Jun 20, 2021