Created
May 1, 2022 20:23
-
-
Save wparad/a1abeb966d9739f37f3eee723021cb6a to your computer and use it in GitHub Desktop.
Remove nulls/undefineds so isEqual works
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
function removeNulls(obj, level = 0) { | |
if (level > 10) { | |
return obj; | |
} | |
if (obj === null || obj === undefined) { | |
return undefined; | |
} | |
if (Array.isArray(obj)) { | |
return obj.map(v => removeNulls(v, level + 1)).filter(v => v !== null && v !== undefined); | |
} | |
if (typeof obj === 'object') { | |
const newObject = {}; | |
Object.keys(obj || {}).forEach(key => { | |
const newValue = removeNulls(obj[key], level + 1); | |
if (newValue !== null && newValue !== undefined) { | |
newObject[key] = newValue; | |
} | |
}); | |
return newObject; | |
} | |
return obj; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment