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

3

15

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"}};
Anticlimax answered 22/11, 2019 at 13:32 Comment(3)
Why not just person1.backpack.color = 'New color'?Lissotrichous
@SebastianKaczmarek Because that would also change person1Cierracig
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.Lissotrichous
C
21
const person2 = {...person1, backpack: {...person1.backpack, color: 'Red' }}
Cierracig answered 22/11, 2019 at 13:36 Comment(0)
T
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)
Toulouselautrec answered 22/11, 2019 at 13:35 Comment(0)
G
-1

You can do like the following code:

// Clone
person = { ...person1 };

// Change properties
person.backpack.color: "New backpack color";
Gaea answered 17/5 at 8:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.