【问题标题】:Using method during copying object by spread operator in map method在 map 方法中通过扩展运算符复制对象期间使用方法
【发布时间】:2020-01-16 15:25:11
【问题描述】:

我正在尝试在我的 Angular 应用程序中使用扩展运算符复制对象并添加新属性。要添加新属性,我想调用一个方法 'addNewProperty(name) 来返回此属性及其值。当我尝试使用扩展运算符调用此方法时,我收到有关 Unexpected 令牌的错误。

这是我的代码

this.files = files['results'].map(file => ({...file, this.addNewProperty(file.name)}));

addNewProperty(name) {
    return {
        extension: name.split('-')[1]
    };
}

另一方面,当我使用“传统”的 Object.assign() 时,一切都很好

this.files = files['results'].map(file => Object.assign(file, this.addNewProperty(file.name)));

你能解释一下,为什么 Object.assign() 可以正常工作,而通过 {..., myMethod()} 复制不起作用?

【问题讨论】:

    标签: javascript angular typescript ecmascript-6


    【解决方案1】:

    您还需要传播新对象。否则你有没有钥匙的东西。

    this.files = files['results'].map(file => ({...file, ...this.addNewProperty(file.name)}));
    //                                                   ^^^
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-05
      • 1970-01-01
      • 1970-01-01
      • 2010-09-15
      • 2019-06-11
      • 2010-10-15
      • 2014-07-31
      • 1970-01-01
      相关资源
      最近更新 更多