有谁知道这是否有简写?
let zx = { a: 1, b: 10};
let as = { a: 20, b: 1};
as += ...zx; //Ideas on a shorthand here?
console.log(as);
期望的结果:{a:21,b:11}
答案 0 :(得分:4)
您可以通过传递Object.keys
函数作为参数,将forEach
方法与arrow
结合使用。
let zx = { a: 1, b: 10};
let as = { a: 20, b: 1};
Object.keys(as).forEach(key => as[key] += zx[key])
console.log(as);
另一种方法是使用reduce
方法。
let zx = { a: 1, b: 10};
let as = { a: 20, b: 1};
as = Object.keys(as).reduce(function(obj, k) {
obj[k] = zx[k] + as[k]
return obj;
}, {});
console.log(as);