【问题标题】:How can i add a property to an inner Object in Typescript with spread operator?如何使用扩展运算符将属性添加到 Typescript 中的内部对象?
【发布时间】:2019-06-13 11:15:47
【问题描述】:

我有以下对象

let car = { year: 2004, type: {name: "BMW"} }

现在我想为内部对象“类型”添加一个属性。我想使用扩展运算符来做到这一点,因为我需要一个新对象,因为现有对象是一个不可变的状态对象。结果应该是:

{ year: 2004, type: {name: "BMW", modell: "3er"}}

我该怎么做?

【问题讨论】:

    标签: javascript typescript spread


    【解决方案1】:
    const car = { year: 2004, type: {name: "BMW"} };
    const modifiedCar = {...car, type: {...car.type, modell: "3er"}};
    

    【讨论】:

      【解决方案2】:

      试试这个:

      (不是不可变的)

      let car = { year: 2004, type: {name: "BMW"} } // changed
      Object.assign(car.type, {modell: "3er"});
      
      console.log(car)

      (不可变)

      let car = { year: 2004, type: {name: "BMW"} } // still the same
      const result = Object.assign({}, car, {type:{...car.type, modell: "3er"}});
      
      console.log(result)

      【讨论】:

        猜你喜欢
        • 2023-02-25
        • 2019-09-03
        • 1970-01-01
        • 2017-09-26
        • 1970-01-01
        • 2021-07-07
        • 2020-03-18
        • 2017-06-12
        • 2018-05-13
        相关资源
        最近更新 更多