Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"}};
like image 803
Tiego A. Nascimento Avatar asked Nov 22 '19 13:11

Tiego A. Nascimento


People also ask

Does spread operator work on nested objects?

The spread operator only creates a new address location for the top-level elements. Any nested objects of newObject are still at the same address locations as the nested objects of object . This means that we need to apply the spread operator at every level we want make a true value copy.

How do you add a property to an object that has spread?

Spread operator syntax “{ … object, property_name: property_value }“ The spread operator allows the creation of a soft copy of an object with existing properties. The Spread operator followed by an inline property definition allows the addition of new properties.

Does spread operator overwrite property?

Using the spread operator to overwrite an object property It's a super clean syntax and easy to see which value we are overwriting. The only thing you must remember while using this method is that the order matters. If we, for instance, put the property we want to overwrite.

Can you use the spread operator on an object?

Use the object spread operator to clone an object or merge objects into one. Cloning is always shallow. When merging objects, the spread operator defines new properties while the Object.


2 Answers

const person2 = {...person1, backpack: {...person1.backpack, color: 'Red' }}
like image 161
Raul Rene Avatar answered Oct 02 '22 16:10

Raul Rene


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)
like image 21
Maxime Girou Avatar answered Oct 02 '22 16:10

Maxime Girou