如何使用扩展运算符将 属性 添加到 Typescript 中的内部对象?
How can i add a property to an inner Object in Typescript with spread operator?
我有以下对象
let car = { year: 2004, type: {name: "BMW"} }
现在我想添加一个 属性 到内部对象 "type"。我想用传播运算符来做到这一点,因为我需要一个新对象,因为现有对象是一个不可变的状态对象。结果应该是:
{ year: 2004, type: {name: "BMW", modell: "3er"}}
我该怎么做?
const car = { year: 2004, type: {name: "BMW"} };
const modifiedCar = {...car, type: {...car.type, modell: "3er"}};
试试这个:
(不是不可变的)
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)
我有以下对象
let car = { year: 2004, type: {name: "BMW"} }
现在我想添加一个 属性 到内部对象 "type"。我想用传播运算符来做到这一点,因为我需要一个新对象,因为现有对象是一个不可变的状态对象。结果应该是:
{ year: 2004, type: {name: "BMW", modell: "3er"}}
我该怎么做?
const car = { year: 2004, type: {name: "BMW"} };
const modifiedCar = {...car, type: {...car.type, modell: "3er"}};
试试这个:
(不是不可变的)
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)