Created
November 6, 2021 22:33
-
-
Save Ricki-BumbleDev/ce9f02985cfeeba32d88bb5facac33ae to your computer and use it in GitHub Desktop.
removeEmpty
This file contains 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
const isTruthy = (value: any) => typeof value === 'number' || Boolean(value); | |
const removeEmpty = (value: any) => { | |
if (Array.isArray(value)) { | |
const newValue = value.map(removeEmpty).filter(isTruthy); | |
if (!newValue.length) { | |
return undefined; | |
} | |
return newValue; | |
} else if (typeof value === 'object' && value !== null && !(value instanceof Date)) { | |
const newValue = Object.fromEntries( | |
Object.entries(value) | |
.map(([key, value]) => [key, removeEmpty(value)]) | |
.filter(([_, value]) => isTruthy(value)) | |
); | |
if (!Object.keys(newValue).length) { | |
return undefined; | |
} | |
return newValue; | |
} else { | |
return isTruthy(value) ? value : undefined; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment