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.
In this example, we use reduce()
method with Object
assign()
as the reducer function to merge all objects inside array
together.
xxxxxxxxxx
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 sourceobject
to atarget
object. It returns the modifiedtarget
object.
In this solution, we use assign()
method with spread syntax (...
) to merge all objects inside the same array into one object.
xxxxxxxxxx
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 }
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.
xxxxxxxxxx
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 }