There are many ways to merge objects in JavaScript.
1. Use()
method:
It can copy properties of one or more objects into the target object. For example:
const obj1 = { a: 1, b: 2 }; const obj2 = { b: 3, c: 4 }; const obj3 = ({}, obj1, obj2); (obj3); // { a: 1, b: 3, c: 4 }
Here we use an empty object ({}) as the first parameter to avoid directly modifying the first object.
2. Use deconstructed assignment syntax:
This method retains the properties of objects with the same key value when merging them, for example:
const obj1 = { a: 1, b: 2 }; const obj2 = { b: 3, c: 4 }; const obj3 = { ...obj1, ...obj2 }; (obj3); // { a: 1, b: 3, c: 4 }
The extension operator is used here, which can deconstruct the properties of one object into another.
3. Use the merge() method in Lodash:
const obj1 = { a: 1, b: 2 }; const obj2 = { b: 3, c: 4 }; const obj3 = _.merge(obj1, obj2); (obj3); // { a: 1, b: 3, c: 4 }
4. For-in loop + manual assignment:
const obj1 = { a: 1, b: 2 }; const obj2 = { b: 3, c: 4 }; const obj3 = {}; for (const key in obj1) { obj3[key] = obj1[key]; } for (const key in obj2) { obj3[key] = obj2[key]; } (obj3); // { a: 1, b: 3, c: 4 }
5. Use () and () methods:
const obj1 = { a: 1, b: 2 }; const obj2 = { b: 3, c: 4 }; const obj3 = {}; (obj1).forEach(key => { obj3[key] = obj1[key]; }); (obj2).forEach(key => { obj3[key] = obj2[key]; }); (obj3); // { a: 1, b: 3, c: 4 }
Finally, it is necessary to remind you that if the object attribute types with the same key value are different when merging objects, for example, one is a string type and the other is a numeric type, it will overwrite the previous attributes, so corresponding processing needs to be made according to project needs.
In addition, if special treatment is required for the properties of the merged object, for example, the property value of the merged object is an array and needs to be merged into a new array, you can use the () method.
const obj1 = { a: [1, 2] }; const obj2 = { a: [3, 4] }; const obj3 = ({}, obj1, { a: () }); (obj3); // { a: [1, 2, 3, 4] }
Or use the extension operator
const obj1 = { a: [1, 2] }; const obj2 = { a: [3, 4] }; const obj3 = {...obj1, a: [..., ...]} (obj3); // { a: [1, 2, 3, 4] }
In addition, if further processing of the attribute values of the merged object, such as deduplication, sorting, etc., you can use methods such as (), () and ().
This is the article about the implementation steps of JavaScript object merging. For more related JS object merging content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!