DEV Community

Discussion on: How to merge objects in JavaScript?

Collapse
 
fgkolf profile image
fgkolf

Thanks for this nice post!

An important note on this subject that i believe you should mention, is the difference on the 2 approaches regarding the mutation of the targeted object.
In your first 2 examples (using spread operator), none of the merged object is mutated (user, address).
In the next 2 examples (Object.assign), the first object (target) of the Object.assign is mutated and will end up being equivalent to the result of Object.assign.
Some times this may be acceptable but in order to provide an example that is equivalent in both approaches you should demonstrate the use of Object.assign with the target being an empty object:

Object.assign({}, user, address);
Enter fullscreen mode Exit fullscreen mode

This is equivalent to

{...user, ...address}
Enter fullscreen mode Exit fullscreen mode

You should also rename Loadash to Lodash :)

Collapse
 
amersikira profile image
Amer Sikira

Thank you for pointing those things out. I didn' t think about that. Really excellent observation!

I've changed Loadash to Lodash, btw. :D