【问题标题】:Object unpacking assignment operation?对象解包赋值操作?
【发布时间】:2022-01-10 03:32:06
【问题描述】:

在 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 中获得的最好的语法?

【问题讨论】:

  • 您要修改obj_b 还是用新对象覆盖它?

标签: javascript object assignment-operator destructuring argument-unpacking


【解决方案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);

【讨论】:

    【解决方案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);

    【讨论】:

      【解决方案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

      【讨论】:

        猜你喜欢
        • 2017-06-18
        • 1970-01-01
        • 2011-07-07
        • 2020-04-16
        • 2017-03-18
        • 2011-07-19
        • 2018-11-02
        • 2021-11-07
        • 1970-01-01
        相关资源
        最近更新 更多