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
x
13
13
1
const obj1 = {
2
a: 1,
3
b: '',
4
c: [],
5
d: null
6
}
7
8
const obj2 = {
9
a: 2,
10
b: null,
11
d: 1
12
}
13
And the effect of merge should be:
JavaScript
1
7
1
const objMerged = {
2
a: 2,
3
b: '',
4
c: [],
5
d: 1
6
}
7
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
1
2
1
_.extend({}, obj1, obj2)
2
and
JavaScript
1
2
1
Object.assign({}, obj1, obj2)
2
Advertisement
Answer
You can use _.mergeWith()
, and in the merge callback only take the 2nd value if it’s not null
:
JavaScript
1
6
1
const obj1 = { a: 1, b: '', c: [], d: null }
2
const obj2 = { a: 2, b: null, d: 1 }
3
4
const result = _.mergeWith({}, obj1, obj2, (o, s) => _.isNull(s) ? o : s)
5
6
console.log(result)
JavaScript
1
1
1
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.11/lodash.min.js"></script>