Skip to content

Instantly share code, notes, and snippets.

@Ricki-BumbleDev
Created November 6, 2021 22:33
Show Gist options
  • Save Ricki-BumbleDev/ce9f02985cfeeba32d88bb5facac33ae to your computer and use it in GitHub Desktop.
Save Ricki-BumbleDev/ce9f02985cfeeba32d88bb5facac33ae to your computer and use it in GitHub Desktop.
removeEmpty
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