Skip to content
Advertisement

How to merge two objects, overriding null values?

I’d like to merge two similar but not identical objects and override null values in one of them, if such exist. For example I’d have these two objects:

JavaScript

And the effect of merge should be:

JavaScript

In other words, the most important source of data in the merged object is obj2 but it lacks some properties from obj1, so they need to be copied and also some of the obj2 values are null so they should be taken from obj1 as well.

EDIT I tried:

JavaScript

and

JavaScript

Advertisement

Answer

You can use _.mergeWith(), and in the merge callback only take the 2nd value if it’s not null:

JavaScript
JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement