Skip to content

Instantly share code, notes, and snippets.

@jamesholcomb
Last active June 30, 2020 16:28
Show Gist options
  • Save jamesholcomb/cbc9a1f0d221cb966caebf9fdc4d804f to your computer and use it in GitHub Desktop.
Save jamesholcomb/cbc9a1f0d221cb966caebf9fdc4d804f to your computer and use it in GitHub Desktop.
Deep merge with comparator to ensure null/undefined data values are patched
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