mindparse mindparse - 1 year ago 59
Javascript Question

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

Answer Source

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);

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download