Skip to content

Instantly share code, notes, and snippets.

@createdbymahmood
Created April 30, 2021 10:15
Show Gist options
  • Save createdbymahmood/636ba68757f4f74ee171efaa2f2b412d to your computer and use it in GitHub Desktop.
Save createdbymahmood/636ba68757f4f74ee171efaa2f2b412d to your computer and use it in GitHub Desktop.
Remove all empty values from an object
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