To combine two objects in JavaScript, you can use various approaches. Here are a few common methods:
Object.assign(): The Object.assign() method combines multiple source objects into a target object by copying the properties from the source objects to the target object.
const obj1 = { a: 1, b: 2 };
const obj2 = { c: 3, d: 4 };
const combinedObj = Object.assign({}, obj1, obj2);
console.log(combinedObj);
// Output: { a: 1, b: 2, c: 3, d: 4 }
In the above example,
Object.assign()
creates a new object by copying the properties ofobj1
andobj2
into an empty object{}
.Spread Operator: The spread operator (...) can be used to merge two or more objects into a new object.
const obj1 = { a: 1, b: 2 };
const obj2 = { c: 3, d: 4 };
const combinedObj = { ...obj1, ...obj2 };
console.log(combinedObj);
// Output: { a: 1, b: 2, c: 3, d: 4 }
Here, the spread operator is used to spread the properties of
obj1
andobj2
into a new object.ES2018 Object Rest/Spread Properties: The Object Rest/Spread Properties syntax allows you to extract specific properties from an object while combining them with other properties.
const obj1 = { a: 1, b: 2 };
const obj2 = { c: 3, d: 4 };
const combinedObj = { ...obj1, ...obj2 };
console.log(combinedObj);
// Output: { a: 1, b: 2, c: 3, d: 4 }
The above example is similar to the spread operator approach.
Lodash merge(): If you are using the Lodash library, you can utilize the
merge()
function to combine objects deeply.
const _ = require('lodash');
const obj1 = { a: 1, b: { c: 2 } };
const obj2 = { b: { d: 3 }, e: 4 };
const combinedObj = _.merge({}, obj1, obj2);
console.log(combinedObj);
// Output: { a: 1, b: { c: 2, d: 3 }, e: 4 }
The
merge()
function merges the properties ofobj1
andobj2
recursively into a new object.
Choose the method that best suits your requirements and the environment you are working in.
No comments:
Post a Comment