最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Flatten an array of objects containing unique keys - Stack Overflow

programmeradmin4浏览0评论

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 bee 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

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 bee 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

Share Improve this question edited Sep 2, 2024 at 17:06 miken32 42.7k16 gold badges121 silver badges172 bronze badges asked Feb 6, 2017 at 13:05 mindparsemindparse 7,24529 gold badges101 silver badges215 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 9

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

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

发布评论

评论列表(0)

  1. 暂无评论