mergeObjectsDeep() was born to be shared.
The Proposed Solution
The function below is the final result of mixing together three main ingredients: the
Array.prototype.reduce() function, Recursion and the Spread Syntax.
You might have noticed two calls to the custom function
isObject(), well, as its signature suggests it is a mono-task function whose body can be disclosed as follows:
A Brief Explanation and A Mandatory Detail
The code works like this:
- When the two values being compared are not both objects, we use the spread syntax to replace the value in
baseObjwith the corresponding value in
incomingObj, if the key under evaluation exists in both of them, otherwise the value of
incomingObjunder evaluation is "pushed" into
baseObjas a new key-value pair.
- When, on the other hand, the two values being compared are both objects, the recursion steps into work jointly with the spread syntax to deeply merge the two child objects.
I want to draw your attention on the
Array.prototype.reduce() function, here used to compose the final, merged object returned by
Have you noticed what the initial value of
baseObj to the
reduce() function as the initial value from which to start constructing the final, merged object, is the little trick in the absence of which
mergeObjectsDeep() would not return the expected result.
New to the Spread Syntax?
So, I strongly encourage you to peruse the "Spread in object literals" section of this carefully written article on the MDN Web Docs site.