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
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)
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With