r/learnjavascript • • Feb 16 '21

Javascript Object Merge

Post image
183 Upvotes

28 comments sorted by

View all comments

Show parent comments

18

u/delventhalz Feb 16 '21

Not exactly. Object.assign or the spread operator like you demonstrated does a shallow merge. This function is a deep merge like lodash's merge.

0

u/[deleted] Feb 16 '21

[deleted]

7

u/delventhalz Feb 16 '21 edited Feb 16 '21

If you are working with only flat objects, then a shallow merge with spread will work fine, yes. If what you want is to recursively merge any nested objects (which is what OP is doing), then spread will not work for you. It will end up just replacing nested objects entirely.

EDIT: a word

2

u/stormfield Feb 17 '21

While this is a neat trick and stuff, at the point this is being done I’d have some real questions about the business purpose of why something like this is needed.

3

u/delventhalz Feb 17 '21

Creating a default object? Combining schemas? Shallow merges are probably more common, but a deep merge is an established pattern with plenty of real world use cases.

Perhaps more importantly, OP specifically demonstrated a deep merge. Responding to him with "but there is a much simpler way to do a shallow merge!" is silly. Completely different pattern.