在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中能得到的最好的语法吗?
发布于 2021-12-03 19:38:37
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);
发布于 2021-12-03 19:45:02
我不认为存在这样的语法,但是如果你需要经常使用这样的东西,你可以用一个实用函数来修补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);
发布于 2021-12-03 20:02:45
另一种选择是使用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
https://stackoverflow.com/questions/70219827
复制相似问题