将同一数组中的多个对象合并为一个对象 [英] Merge multiple objects inside the same array into one object
本文介绍了将同一数组中的多个对象合并为一个对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
var arrObj = [{a:1, b:2},{c:3, d:4},{e:5, f:6}];
如何将其合并为一个obj?
how can i merge this into one obj?
//mergedObj = {a:1, b:2, c:3, d:4, e:5, f:6}
推荐答案
您可以使用 Array.prototype.reduce
像这样
You can use Array.prototype.reduce
like this
var resultObject = arrObj.reduce(function(result, currentObject) {
for(var key in currentObject) {
if (currentObject.hasOwnProperty(key)) {
result[key] = currentObject[key];
}
}
return result;
}, {});
console.log(resultObject);
# { a: 1, b: 2, c: 3, d: 4, e: 5, f: 6 }
此解决方案只是收集结果
中每个对象中的所有键及其值,最后将其作为结果返回给我们。
This solution, simply gathers all the keys and their values in every object in the result
, which is finally returned to us as the result.
此检查
if (currentObject.hasOwnProperty(key)) {
是确保我们不在结果中包含所有继承的可枚举属性所必需的。
is necessary to make sure that we are not including all the inherited enumerable properties in the result.
如果您的环境支持 Object.assign
,然后你可以用简洁的方式做同样的事情这个
If your environment supports Object.assign
, then you can do the same in a succinct way like this
const arrObj = [{a: 1, b: 2}, {c: 3, d: 4}, {e: 5, f: 6}];
console.log(arrObj.reduce(function(result, current) {
return Object.assign(result, current);
}, {}));
// If you prefer arrow functions, you can make it a one-liner ;-)
console.log(arrObj.reduce(((r, c) => Object.assign(r, c)), {}));
// Thanks Spen from the comments. You can use the spread operator with assign
console.log(Object.assign(...arrObj));
这篇关于将同一数组中的多个对象合并为一个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文