Combine Two or more JSON Objects in JavaScript
In this quick tutorial, we’ll learn how to combine two or more JSON object into one object in JavaScript.
Object.assign()
The Object.assign
is the most straightforward approach to add two or more objects.
var obj1 = { eat: 'pizza', drink: 'coke' };
var obj2 = { drive: 'car', ride: 'bus' }
var obj3 = { pet: 'dog' }
var obj4 = Object.assign({}, obj1, obj2, obj3);
console.log(obj4);
// {eat: "pizza", drink: "coke", drive: "car", ride: "bus", pet: "dog"}
Spread Operator (…)
If you have started using ES6 then it is recommended to use spread operator (…) which is more handy to combine two or more objects.
var obj1 = { eat: 'pizza', drink: 'coke' };
var obj2 = { drive: 'car', ride: 'bus' }
var obj3 = { pet: 'dog' }
var obj4 = { ...obj1, ...obj2, ...obj3 };
console.log(obj4);
// {eat: "pizza", drink: "coke", drive: "car", ride: "bus", pet: "dog"}