Map array to object

JavaScript, Array, Object · Oct 21, 2020

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

  • Use Array.prototype.reduce() to apply fn to each element in arr and combine the results into an object.
  • Use el as the key for each property and the result of fn as the value.
const mapObject = (arr, fn) =>
  arr.reduce((acc, el, i) => {
    acc[el] = fn(el, i, arr);
    return acc;
  }, {});
mapObject([1, 2, 3], a => a * a); // { 1: 1, 2: 4, 3: 9 }

More like this

  • 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

  • Map an array to an object

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

    JavaScript, Array · Feb 4, 2023

  • Array to object based on key

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

    JavaScript, Array · Jun 27, 2021