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"}};
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.
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.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With