Merging Objects in JavaScript

There are several ways to combine JavaScript objects:

Object.assign() method: This method copies all enumerable own properties from one or more source objects to a target object, and returns the target object.

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

Spread operator: The spread operator (...) can be used to spread the properties of an object into a new object, or to merge multiple objects into a single object.

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

Object.create() method: This method creates a new object with the specified prototype object and properties.

let obj1 = { a: 1, b: 2 };
let obj2 = Object.create(obj1);
console.log(obj2); // { }
console.log(obj2.a); // 1

ES6 destructuring: Destructuring is a feature of ES6 that allows you to extract properties from an object and assign them to variables. You can use destructuring to merge two objects by extracting the properties of one object and then spreading them into the other object.

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

Lodash library: Lodash is a JavaScript library that provides a variety of utility functions, including functions for merging objects. The _.merge() function can be used to merge multiple objects into a single object.

let obj1 = { a: 1, b: 2 };
let obj2 = { c: 3, d: 4 };
let obj3 = _.merge({}, obj1, obj2);
console.log(obj3); // { a: 1, b: 2, c: 3, d: 4 }