var arrObj = [{a:1, b:2},{c:3, d:4},{e:5, f:6}];
如何将其合并为一个obj?
//mergedObj = {a:1, b:2, c:3, d:4, e:5, f:6}
如果您的环境支持Object.assign,那么您可以像这样简洁地进行操作
Object.assign
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.reduce这样的
Array.prototype.reduce
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,最终将结果返回给我们。
result
这张支票
if (currentObject.hasOwnProperty(key)) {
有必要确保我们在结果中不包括所有继承的可枚举属性。