将同一数组内的多个对象合并为一个对象 [英] Merge multiple objects inside the same array into one object

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

问题描述

var arrObj = [{a:1, b:2},{c:3, d:4},{e:5, f:6}];

如何将其合并为一个对象?

how can i merge this into one obj?

//mergedObj = {a:1, b:2, c:3, d:4, e:5, f:6}

推荐答案

如果您的环境支持 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));

ES5 解决方案:

您可以使用Array.prototype.像这样减少

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 }

这个解决方案,简单地收集result中每个对象中的所有键和它们的值,最后作为结果返回给我们.

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.

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

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