Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flatten an array of objects containing key\values

Say I have the follow array of objects storing a single key\value pair:

var someArray = [
    {foo: 1},
    {bar: 2}
];

I would like to flatten this array into a single object, where each key from the original objects become a property of the new single object like so:

someObject = {
    foo: 1,
    bar: 2
}

I will always have unique keys, and only ever one key\value pairing.

I know if I loop over the array in a foreach, then I can only access the index and value of the item, e.g.

0: {foo: 1}

I want to be able to loop over, and when accessing the item read the key and value separately so I can append onto my new object.

I feel like lodash should be able to help here, but I'm struggling to find whic of their methods could help.

Can someone point me in the right direction?

Thanks

like image 533
mindparse Avatar asked Dec 15 '22 00:12

mindparse


2 Answers

No need for lodash here you can just use Object.assign() and spread syntax.

var someArray = [
  {foo: 1},
  {bar: 2}
];
var obj = Object.assign({}, ...someArray)
console.log(obj)

You can also use apply instead of spread syntax

var obj = Object.assign.apply({}, someArray)

var someArray = [
  {foo: 1},
  {bar: 2}
];
var obj = Object.assign.apply({}, someArray)
console.log(obj)
like image 168
Nenad Vracar Avatar answered Dec 28 '22 12:12

Nenad Vracar


You could iterate and use Object.assign to get a new object with all properties.

var someArray = [{ foo: 1 }, { bar: 2 }],
    result = someArray.reduce(function (r, a) {
        return Object.assign(r, a);
    }, {});

console.log(result);
like image 35
Nina Scholz Avatar answered Dec 28 '22 12:12

Nina Scholz