Created
January 30, 2020 12:01
-
-
Save Akiyamka/8684839bff3b535925db9749a3d2df98 to your computer and use it in GitHub Desktop.
Safety merge objects
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
export default function safeMerge(obj1, obj2) { | |
const keys = Object.keys(obj2).concat(Object.keys(obj1)); | |
const isInvalid = val => val === undefined || Number.isNaN(val) || val === null; | |
return keys.reduce((acc, key) => { | |
acc[key] = !isInvalid(obj2[key]) | |
? obj2[key] | |
: obj1[key]; | |
if (isInvalid(acc[key])) { | |
delete acc[key]; | |
} | |
return acc; | |
}, {}); | |
} | |
/** | |
* Examples: | |
*/ | |
safeMerge( | |
{ foo: 'bar', fizz: 'buzz' }, | |
{ magic: 'xyzzy', fizz: undefined, foo: null } | |
) | |
// { foo: 'bar', fizz: 'buzz', magic: 'xyzzy' } | |
safeMerge( | |
{ magic: 'xyzzy', foo: null }, | |
{ fizz: 'buzz' } | |
) | |
// { magic: 'xyzzy', fizz: 'buzz' } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment