Skip to content

Instantly share code, notes, and snippets.

@memandip
Created July 29, 2021 09:30
Show Gist options
  • Save memandip/e86548b3229f40d7daf48ad071502150 to your computer and use it in GitHub Desktop.
Save memandip/e86548b3229f40d7daf48ad071502150 to your computer and use it in GitHub Desktop.
Remove empty or undefined elements from nested object
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