Search code examples
javascriptecmascript-6javascript-objects

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"}};

Solution

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