Flatten an array of objects containing key\values

孤街浪徒 提交于 2019-12-10 10:17:53

问题


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


回答1:


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



回答2:


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)



回答3:


This can be done quickly using reduce and Object assign:

var someArray = [
    {foo: 1},
    {bar: 2}
];
var result = someArray.reduce((acc, obj) => Object.assign(acc, obj), {})
console.log(result)
.as-console-wrapper { max-height: 100% !important; top: 0; }


来源:https://stackoverflow.com/questions/42068529/flatten-an-array-of-objects-containing-key-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!