将具有对象的数组展平为1个对象 [英] Flatten array with objects into 1 object

查看:118
本文介绍了将具有对象的数组展平为1个对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定输入:

[{ a: 1 }, { b: 2 }, { c: 3 }]

如何退货:

{ a: 1, b: 2, c: 3 }

对于数组使用lodash 这不是问题,但这里我们有对象数组。

For arrays it's not a problem with lodash but here we have array of objects.

推荐答案

使用 对象.assign

let merged = Object.assign(...arr); // ES6 (2015) syntax

var merged = Object.assign.apply(Object, arr); // ES5 syntax

注意 Object.assign 尚未在许多环境中实施,您可能需要对其进行填充(使用core-js,另一个polyfill或使用MDN上的polyfill)。

Note that Object.assign is not yet implemented in many environment and you might need to polyfill it (either with core-js, another polyfill or using the polyfill on MDN).

您提到了lodash ,所以值得指出它附带一个 _。assign 函数,用于此目的:

You mentioned lodash, so it's worth pointing out it comes with a _.assign function for this purpose that does the same thing:

 var merged = _.assign.apply(_, [{ a: 1 }, { b: 2 }, { c: 3 }]);

但我真的推荐新的标准库方式。

But I really recommend the new standard library way.

这篇关于将具有对象的数组展平为1个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆