17

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"}}; 
3
  • Why not just person1.backpack.color = 'New color'? Commented Nov 22, 2019 at 13:34
  • 2
    @SebastianKaczmarek Because that would also change person1 Commented Nov 22, 2019 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. Commented Nov 22, 2019 at 13:42

3 Answers 3

24
const person2 = {...person1, backpack: {...person1.backpack, color: 'Red' }} 
Sign up to request clarification or add additional context in comments.

Comments

7

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)

Comments

-2

You can do like the following code:

// Clone person = { ...person1 }; // Change properties person.backpack.color: "New backpack color"; 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.