Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

just-flush-recursively / just-flush-deep / just-deep-flush / just-flush-object? #517

Open
kachkaev opened this issue Nov 26, 2022 · 2 comments

Comments

@kachkaev
Copy link

Hi @angus-c, great repo! 馃挴

I bumped into just-flush which was very close a function I needed. I wonder if you鈥檇 be open to accept a PR with a recursive version of the function, WDYT?

const fn = require('just-...')

fn([1, undefined, 2, [null], 3, NaN, 0]) // fn([1, 2, [], 3, 0])
fn({a: 2, b: null, c: 4, d: undefined, e: { x: 2, y: null, z: undefined }}) // flush({a: 2, c: 4, e: { x: 2 }})

It might be also useful to consider a mode when nullish items are not removed from arrays, but not 100% sure about this 馃

-fn([1, undefined, 2, [null], 3, NaN, 0]) // fn([1, 2, [], 3, 0])
+fn2([1, undefined, 2, [null], 3, NaN, 0]) // fn([1, 2, [null], 3, 0])
@kachkaev
Copy link
Author

My current solution is this:

/**
 * Recursively removes null and undefined values from an object
 * https://stackoverflow.com/a/54707141/1818285
 * TODO: consider refactoring (avoid conversion to string)
 */
export const deepClean = <T>(obj: T): OmitNullable<T> =>
  JSON.parse(
    JSON.stringify(obj, (key, value: unknown) =>
      value === null || value === undefined ? undefined : value,
    ),
  ) as OmitNullable<T>;

It works well for relatively small objects, but obviously does not scale if a JSON is very large. I鈥檓 looking for some third-party package that would save me from copying this small helper function between repos.

@angus-c
Copy link
Owner

angus-c commented Dec 29, 2022

Hi @kachkaev, thanks for the nice words!
Yes I think this would be a useful util. I think a new function just-flush-recursive would be the best way, to keep the old one clean.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants