Created
July 29, 2021 09:30
-
-
Save memandip/e86548b3229f40d7daf48ad071502150 to your computer and use it in GitHub Desktop.
Remove empty or undefined elements from nested object
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 const removeEmptyOrUndefined = (obj: any) => { | |
let finalObj: any = {}; | |
Object.keys(obj).forEach((key) => { | |
if (obj[key] && typeof obj[key] === 'object') { | |
const nestedObj = removeEmptyOrUndefined(obj[key]); | |
if (Object.keys(nestedObj).length) { | |
finalObj[key] = nestedObj; | |
} | |
} else if (obj[key] !== '' && obj[key] !== undefined && obj[key] !== null) { | |
finalObj[key] = obj[key]; | |
} | |
}); | |
return finalObj; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment