In one of the previous week’s articles, I noticed Defu is used in unbuild source code to merge objects. This got me wondering how this is different to lodash._merge. In this article, we will look at their differences. I created a Codesandbox repository for the purposes of this article. Let’s get started.
This method is like_.assign except that it recursively merges own and inherited enumerable string keyed properties of source objects into the destination object. Source properties that resolve to undefined are skipped if a destination value exists. Array and plain object properties are merged recursively. Other objects and value types are overridden by assignment. Source objects are applied from left to right. Subsequent sources overwrite property assignments of previous sources.
At this point, I would investigate if arrays are merged in defu or if it only deals with objects. Let’s pick the example from lodash._merge and see the results.
In this sandbox example — https://codesandbox.io/p/devbox/yn9ds8, I have setup the defu and lodash._merge and below is a screenshot of my attempt to merge arrays recursively using Defu.
Defu cannot merge arrays recrusively, I would use Defu stricly to merge objects only. The key difference here is:
What’s the count of array items in these two examplse? lodash._merge has only two items, whereas defu has four items, each item being an object. Something to keep in mind, I guess.
Hey, my name is Ramu Narasinga. I study large open-source projects and create content about their codebase architecture and best practices, sharing it through articles, videos.