提问人:Maurdekye 提问时间:12/4/2021 更新时间:12/4/2021 访问量:245
对象解包赋值操作?
Object unpacking assignment operation?
问:
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 中得到的最好的语法?
答:
3赞
Nina Scholz
12/4/2021
#1
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赞
Christian Fritz
12/4/2021
#2
我不认为存在任何这样的语法,但是如果您需要经常使用类似的东西,您可以使用实用程序函数对类进行猴子修补: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);
0赞
Youssef Bouhjira
12/4/2021
#3
另一种选择是使用它不是运算符,但它可以完成工作:Object.assign
Object.assign(obj_b, obj_a)
// {test: 'one', other: 'three', property: 'two'}
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
评论
obj_b