如何使用传播运算符更改对象的嵌套属性?

时间:2019-11-22 13:32:34

标签: javascript ecmascript-6 javascript-objects

这是我情况的干净版本:

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 个答案:

答案 0 :(得分:3)

您必须首先在下面散布该物业

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)

答案 1 :(得分:3)

const person2 = {...person1, backpack: {...person1.backpack, color: 'Red' }}