Thomas Johnson Thomas Johnson - 4 months ago 22
Javascript Question

Create object from forEach

I'm trying to figure out if there's a way to rewrite this code as a single object creation:

my_array = [
{key: 1, value: "foo"},
{key: 2, value: "bar"}
];

let my_obj = {};
my_array.forEach((elem) => {
my_obj[elem.key] = elem.value;
});


What I'd like to do is something like:

my_array = [
{key: 1, value: "foo"},
{key: 2, value: "bar"},
];

const my_obj = ...?


Is there a way to do a one-shot conversion that's equivalent to the
forEach
call?

Answer

You can achieve this using Array.prototype.reduce():

var my_array = [{key: 1, value:"foo"}, {key: 2, value:"bar"}];
  
var my_object = my_array.reduce(function(prev, curr) {
  prev[curr.key] = curr.value;
  return prev;
}, {});

console.log(my_object); // {"1": "foo", "2": "bar"}


Alternatively, using ES6 syntax:

const my_object = my_array.reduce((prev, curr) => {
    prev[curr.key] = curr.value;
    return prev;
}, {});
Comments