There are several ways to merge objects in JavaScript. One common method is to use the spread operator (‘…’) to combine the properties of multiple objects into a new one. Here is an example of how you can use the spread operator to merge two objects:

const obj1 = { a: 1, b: 2 };
const obj2 = { b: 3, c: 4 };
const mergedObj = { ...obj1, ...obj2 };
console.log(mergedObj); // { a: 1, b: 3, c: 4 }

In the example above, the properties of ‘obj1’ and ‘obj2’ are spread into a new object, ‘mergedObj’. If both objects have a property with the same key, the property from the second object will overwrite the one from the first object. In the example, obj1.b is overwritten by obj2.b

Another method is to use Object.assign() method:

const obj1 = { a: 1, b: 2 };
const obj2 = { b: 3, c: 4 };
const mergedObj = Object.assign({}, obj1, obj2);
console.log(mergedObj); // { a: 1, b: 3, c: 4 }

This method works similarly to the spread operator, but it requires you to pass an empty object as the first argument to create a new object to merge the properties into.

You can also use a library like lodash which has a merge function that allows you to merge multiple objects

const _ = require('lodash');
const obj1 = { a: 1, b: 2 };
const obj2 = { b: 3, c: 4 };
const mergedObj = _.merge(obj1, obj2);
console.log(mergedObj); // { a: 1, b: 3, c: 4 }

It’s important to note that these methods merge objects at the first level, if you want to merge nested objects you will need to use a different approach.

Also Read:

Categorized in: