简体   繁体   中英

How to change nested property of an object using spread operator?

This is a clean version of the my situation:

const person1 = {
    name: "Person1 Name",
    hairColor: "Brown",

    backpack: {
        color: "Army-Green",
        content: [
            "item1",
            "item2",
            "..."
        ]
    }
}

And I'm trying to change only the backpack color

I already tried this code below but not success:

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"}};
const person2 = {...person1, backpack: {...person1.backpack, color: 'Red' }}

You must spread the property first liek this below

 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM