Created
April 30, 2021 10:15
-
-
Save createdbymahmood/636ba68757f4f74ee171efaa2f2b412d to your computer and use it in GitHub Desktop.
Remove all empty values from an 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
import flat, { unflatten } from "flat"; | |
import { reduceRight } from "lodash"; | |
import { | |
pipe, | |
reject, | |
isNil, | |
isEqual, | |
get, | |
fromPairs, | |
entries, | |
last, | |
} from "lodash/fp"; | |
const object = { | |
a: { | |
b: { | |
arr: [], | |
c: { | |
d: null, | |
e: 1, | |
f: false, | |
g: undefined, | |
h: 0, | |
}, | |
}, | |
}, | |
}; | |
const or = (...fns: any[]) => (args: any) => | |
reduceRight( | |
fns, | |
(truth, f) => { | |
return truth || f(args); | |
}, | |
false | |
); | |
const isEmptyArray = pipe(get("length"), isEqual(0)); | |
const pruneObject = pipe( | |
flat, | |
entries, | |
reject(pipe(last, or(isNil, isEmptyArray))), | |
fromPairs, | |
unflatten | |
); | |
console.log(pruneObject(object)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment