m0rk4i
October 8, 2019, 3:19am
1
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
pmw57
October 8, 2019, 3:27am
3
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]
m0rk4i
October 8, 2019, 3:34am
4
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
pmw57
October 8, 2019, 3:46am
6
Not that I know of. But just in case, can you come up with a meaningful example that demonstrates a problem?
pmw57
October 8, 2019, 3:48am
7
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
pmw57
October 8, 2019, 4:20am
9
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'})
};