Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 348
Thomas Johnson Avatar asked Aug 03 '16 20:08

Thomas Johnson


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;
}, {});
like image 110
TimoStaudinger Avatar answered Oct 12 '22 20:10

TimoStaudinger


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 }, then uses Object.assign to merge them into one object. (The spread operator is used as Object.assign expects a variable list of arguments.)

like image 27
gcampbell Avatar answered Oct 12 '22 20:10

gcampbell


You can use the reduce function. It should work like this:

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" }
like image 2
JuHwon Avatar answered Oct 12 '22 20:10

JuHwon