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.
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.
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.
A "shallow" merge means you are just merging the top level properties. A "deep" merge, means you are recursively drilling down through all of the sub-objects and performing merges on them as well.
Probably needs an example to click. Let's say we have two incomplete objects we want to merge.
So, we started with all vegeta properties and then overwrote them with goku properties when they existed. This includes the move property. We just took the whole object.
Now let's do a deep merge. I'll use lodash's merge instead of writing my own.
Mostly the same, but notice that the merge continued down into the move object. Since Vegeta's move had a color, but Goku's did not, we kept the color.
One other difference worth noting: in a shallow merge nested objects are not cloned. That means goku and vegitoshare a move object. If we mutate one, we will change the other.
0
u/[deleted] Feb 16 '21
[deleted]