13

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"}};
Sebastian Kaczmarek
  • 8,120
  • 4
  • 20
  • 38
  • Why not just `person1.backpack.color = 'New color'`? – Sebastian Kaczmarek Nov 22 '19 at 13:34
  • @SebastianKaczmarek Because that would also change `person1` – Raul Rene Nov 22 '19 at 13:38
  • 1
    Ahh I see, you need a new object but with changed property. Then answers below show examples of how to do it properly. However, keep in mind that the spread operator is just a *shallow* copy of an object which means that nested objects are not deeply copied. Instead, only references to them are copied so there may be a situation where you change this nested object in the parent object copy and both `person1` and `person` will be affected by this change. – Sebastian Kaczmarek Nov 22 '19 at 13:42

2 Answers2

15
const person2 = {...person1, backpack: {...person1.backpack, color: 'Red' }}
Raul Rene
  • 10,014
  • 9
  • 53
  • 75
6

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)
Maxime Girou
  • 1,511
  • 2
  • 16
  • 32