JavaScript - merge multiple objects inside the same array into one object
In this article, we would like to show you how to merge multiple objects inside the same array into one object in JavaScript.
1. Using reduce() with Object assign()
In this example, we use reduce() method with Object assign() as the reducer function to merge all objects inside array together.
// ONLINE-RUNNER:browser;
const array = [
{ a: 1, b: 2 },
{ c: 3, d: 4 },
{ e: 5, f: 6 },
];
const result = array.reduce((target, source) => Object.assign(target, source), {});
console.log(JSON.stringify(result, null, 4)); // { a: 1, b: 2, c: 3, d: 4, e: 5, f: 6 }
Note:
The
Object.assign()method copies all enumerable own properties from sourceobjectto atargetobject. It returns the modifiedtargetobject.
2. Using Object assign() with spread syntax (...)
In this solution, we use assign() method with spread syntax (...) to merge all objects inside the same array into one object.
// ONLINE-RUNNER:browser;
const array = [
{ a: 1, b: 2 },
{ c: 3, d: 4 },
{ e: 5, f: 6 },
];
const result = Object.assign({}, ...array);
console.log(JSON.stringify(result, null, 4)); // { a: 1, b: 2, c: 3, d: 4, e: 5, f: 6 }
3. Solution for older versions of JavaScript
In this solution, we use reduce() method to gather all the keys and their values from every object in the resultObject. hasOwnProperty() method is used to check that we are not including all the inherited enumerable properties in the result.
// ONLINE-RUNNER:browser;
var array = [
{ a: 1, b: 2 },
{ c: 3, d: 4 },
{ e: 5, f: 6 },
];
var result = array.reduce(function(resultObject, currentObject) {
for (var key in currentObject) {
if (currentObject.hasOwnProperty(key)) {
resultObject[key] = currentObject[key];
}
}
return resultObject;
}, {});
console.log(JSON.stringify(result, null, 4)); // { a: 1, b: 2, c: 3, d: 4, e: 5, f: 6 }