这是我的情况的一个干净版本:const person1 = { name: "Person1 Name", hairColor: "Brown", backpack: { color: "Army-Green", content: [ "item1", "item2", "..." ] }}我试图只改变背包的颜色我已经在下面尝试过这段代码,但没有成功:person = {...person1, backpack.color: "New backpack color"}};person = {...person1, backpack: {...backpack, color: "New backpack color"}};person = {...person1, backpack: {color: "New backpack color"}};person = {...person1, backpack = {...backpack, color: "New backpack color"}};
2 回答
长风秋雁
TA贡献1757条经验 获得超7个赞
const person2 = {...person1, backpack: {...person1.backpack, color: 'Red' }}
互换的青春
TA贡献1797条经验 获得超6个赞
您必须首先在下面传播该属性
const person1 = {
name: "Person1 Name",
hairColor: "Brown",
backpack: {
color: "Army-Green",
content: [
"item1",
"item2",
"..."
]
}
}
const person = {...person1, backpack : {...person1.backpack, color : "Red"}}
console.log(person)
添加回答
举报
0/150
提交
取消