两个对象属性值相同的合并之后再相加应该怎么写呢代码如下

let obj1 = {

value: 10,
age: 20,
name: 30,
qwe:10

}
let obj2 = {

value: 1,
age: 2,
name: 3,
test:10

}

//得到数据相加如下:
let obj = {

value: 11,
age: 22,
name: 33,
qwe:10,
test:10

}

最佳答案

function  test(obj1, obj2) {
    let temp = {...obj1, ...obj2}
    Object.keys(temp).forEeach(key => {
    temp[key] = (obj1[key] || 0) + (obj2[key] || 0)
    })
    
    return temp
}
 test(obj1, obj2)