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:

const obj1 = {
    a: 1,
    b: '',
    c: [],
    d: null
}

const obj2 = {
    a: 2,
    b: null,
    d: 1
}

And the effect of merge should be:

const objMerged = {
    a: 2,
    b: '',
    c: [],
    d: 1
}

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:

_.extend({}, obj1, obj2) 

and

Object.assign({}, obj1, obj2)

Advertisement

Answer

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

const obj1 = { a: 1, b: '', c: [], d: null }
const obj2 = { a: 2, b: null, d: 1 }

const result = _.mergeWith({}, obj1, obj2, (o, s) => _.isNull(s) ? o : s)

console.log(result)
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.11/lodash.min.js"></script>
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement