js merge two objects

You can use Object.assignthe method to merge two objects. Object.assignThe method accepts a target object and one or more source objects as parameters, copies the properties of the source object to the target object, and returns the target object. If there are duplicate attribute names, the later attributes will overwrite the previous ones.

Sample code:

const obj1 = {
    
     a: 1, b: 2 }
const obj2 = {
    
     b: 3, c: 4 }

const result = Object.assign({
    
    }, obj1, obj2)

console.log(result) // 输出:{ a: 1, b: 3, c: 4 }

In the above code, we first define two objects obj1and obj2, then use Object.assignthe method to merge them into a new object result, and print out the merged result. Note that {}a new object is created as the target object by passing an empty object as the first parameter. This is because Object.assignthe method will modify the value of the first parameter. If we don't want to modify the original object, we need to pass a new empty object as the target object.

Guess you like

Origin blog.csdn.net/qq_27487739/article/details/131100351