In this tutorial, we’ll look at a couple of different ways to merge multiple objects together in JavaScript.
If you need to merge a couple of objects together, you can use the spread operator on both objects:
const obj1 = { a: 1, b: 2 };
const obj2 = { b: 3, c: 4 };
const merged = { ...obj1, ...obj2 }; // { a: 1, b: 3, c: 4 };
A new object is created and stored in the merged variable.
Notice what happened to property b in the output?
As it is common to both objects, it took on the value of the second object in the final output so the ordering of the objects is important if you have non-unique properties.
You can of course add as many objects as you like:
const merged = { ...obj1, ...obj2, ...obj3, ...obj4 };;
Using Object.assign()
An alternative is to use the Object.assign() function (for example if you’re running code in an environment where the spread operator isn’t available).
It works pretty much the same way:
const merged = Object.assign({}, obj1, obj2, obj3, obj4);
All of the objects will get merged into the first argument provided to Object.assign() so if you don’t want to mutate an existing object, you can provide an empty object like above.