Spread Operator(Object inside Object)

const user= {
        name: "Diego",
        age: 23,
        address: {
          city: "Toronto",
          country: "Canada",
          phone: "9119119111"
         }
      };

I’m trying to use the spread operator to change only the city property of the address Object
If I try const user2 = {...user, address: { city: "Quebec"}};
I’m gonna lose the other properties of address Object.
Any hint to solve problems with Objects inside Objects?

Thx in advance

How about

const user2 = {...user, address: { ...user.address, city: 'Quebec' }};
2 Likes

Clarity might be gained by using Object.assign

user2 = {...user, address: Object.assign(user.address, { city: "Quebec"})};

[edit]This modifies the original object, and isn’t helpful.[/edit]

WoW! Love this community! You guys are damn fast
Thank so much

@kevcomedia I understood your code ty!
@pmw57 I will study this Object.assign… never saw that syntanx but thx for fast replying

Wouldn’t that modify the original object’s address?

1 Like

Not that I know of. But just in case, can you come up with a meaningful example that demonstrates a problem?

Oh yes it does modify the original. Ignore my object.assign idea.

You can use an empty object as the first argument, then pass the other objects next.

Object.assign({}, user.address, {city: 'Quebec'})
1 Like

Yes, that now works properly. When comparing that with the spread address, the spread is easily seen in this case to be superior to using Object.assign.

Spread:

const user2 = {...user, address: { ...user.address, city: 'Quebec' }};

Object.assign:

const user2 = {
    ...user,
    address: Object.assign({}, user.address, {city: 'Quebec'})
};