Last active
June 30, 2020 16:28
-
-
Save jamesholcomb/cbc9a1f0d221cb966caebf9fdc4d804f to your computer and use it in GitHub Desktop.
Deep merge with comparator to ensure null/undefined data values are patched
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { mergeWith, isNil } from "lodash" | |
var existing = { | |
a: 1, | |
b: 2, | |
d: { | |
a: 1, | |
b: [], | |
c: { test1: 123, test2: 321 } | |
}, | |
f: 5, | |
g: 123, | |
i: 321, | |
j: [1, 2] | |
} | |
var data = { | |
b: 3, | |
c: undefined, | |
d: { | |
b: { first: 'one', second: 'two' }, | |
c: { test2: 222 } | |
}, | |
e: { one: 1, two: 2 }, | |
f: [], | |
g: (void 0), | |
h: /abc/g, | |
i: null, | |
j: [3, 4] | |
} | |
const res = mergeWith( | |
existing, | |
data, | |
(a, b) => isNil(b) ? null : undefined) | |
) | |
/* | |
{ | |
a: 1, | |
b: 3, | |
d: | |
{ a: 1, | |
b: [ first: 'one', second: 'two' ], | |
c: { test1: 123, test2: 222 } }, | |
f: [], | |
g: 123, | |
i: null, | |
j: [ 3, 4 ], | |
c: null, | |
e: { one: 1, two: 2 }, | |
h: /abc/g | |
} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment