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:
- How To Get The Last Character Of A String In JavaScript
- Remove The Last Character Of A String In JavaScript
- How To Validate An Email Address In JavaScript
- How To Check If An Input Field Is Empty In JavaScript
- Check If An Input Field Is A Number In JavaScript
- Confirm Password Validation In JavaScript
- How To Print A PDF File Using JavaScript
- Calculate The Number Of Days Between Two Dates In JavaScript
- How To Compare Two Dates In JavaScript
- Calculate Age With Birth Date YYYYMMDD In JavaScript
- How To Append or Add Text To A DIV Using JavaScript
- How To Get The Text Of HTML Element In JavaScript
- How To Change The Text Inside A DIV Element In JavaScript
- Show/Hide Multiple DIVs In JavaScript
- Show A DIV After X Seconds In JavaScript
- Display A JavaScript Variable In An HTML Page
- How To Generate A Random Number In JavaScript
- Bubble Sort In JavaScript
- Insertion Sort In JavaScript
- Selection Sort In JavaScript
- How To Remove A Specific Item From An Array In JavaScript
- Merge Sort In JavaScript
- Round To 2 Decimal Places In JavaScript
- SetInterval() and setTimeout() Methods In JavaScript
- Generate A Unique ID In JavaScript
- Caesar Cipher In JavaScript
- How To Reverse A String In JavaScript
- How To Loop Through A Plain JavaScript Object
- How To Open A URL In A New Tab Using JavaScript?