对象解构赋值操作?

3
有没有类似 JavaScript 的东西?基本上,我正在寻找这样的东西:
let obj_a = {test: "one", property: "two"};
let obj_b = {test: "1", other: "three"};
let obj_b ...= obj_a; // would be the equivalent of obj_b = {...obj_b, ...obj_a}

有没有类似于这样的内置语法,或者ES6中这是最好的方法了?


1
你想修改 obj_b 还是用一个新对象覆盖它? - Bergi
3个回答

3

Object.assign 可以实现此功能。

let obj_a = { test: "one", property: "two" },
    obj_b = { test: "1", other: "three" };

Object.assign(obj_b, obj_a);

console.log(obj_b);


0

0

我不认为存在这样的语法,但如果你需要经常使用类似的东西,你可以通过猴子补丁(monkey-patch)Object类来添加一个实用函数:

Object.prototype.merge = function(x) { Object.assign(this, x) }
let obj_a = {test: "one", property: "two"};
obj_a.merge({test: "1", other: "three"});
console.log(obj_a);


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接