Create object from forEach

I am trying to figure out if there is a way to rewrite this code as creating a single object:

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 would 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-time conversion equivalent to calling forEach ?

+6
source share
3 answers

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; }, {}); 
+7
source

You can use the reduce function. It should work as follows:

 my_array = [ {key: 1, value: "foo"}, {key: 2, value: "bar"} ]; let my_obj = my_array.reduce(function(obj, elem) { obj[elem.key] = elem.value; return obj; }, {}); // my_obj = { "1": "foo", "2": "bar" } 
+1
source

In ES6, you can use Object.assign :

 const obj = Object.assign({}, ...my_array.map(x => ({ [x.key]: x.value }))); // Or: const obj = Object.assign({}, ...my_array.map(({ key, value }) => ({ [key]: value }))); 

This converts each { key: foo, value: bar } to { foo: bar } , and then uses Object.assign to combine them into a single object. (The distribution operator is used as Object.assign expects a variable argument list.)

+1
source

All Articles