Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@kra3
Created May 18, 2018 09:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kra3/21239fca17b48283e42eca25bd45b51c to your computer and use it in GitHub Desktop.
Save kra3/21239fca17b48283e42eca25bd45b51c to your computer and use it in GitHub Desktop.
remove false values from nested objects recursively
import _isObjectLike from 'lodash/isObjectLike';
import _size from 'lodash/size';
function removeEmptyValuesRecursively(obj) {
return removeEmptyValues(obj);
function isFalsy(val) {
// return true, if val is empty [], empty {} or null
return !_isObjectLike(val) ? val === null : _size(val) <= 0;
}
function removeEmptyValues(data) {
if (_isObjectLike(data)) {
const result = Object.entries(data).reduce((res, [key, value]) => {
const newValue = removeEmptyValues(value);
if (!isFalsy(newValue)) {
res[key] = newValue;
}
return res;
}, Array.isArray(data) ? [] : {});
return isFalsy(result) ? undefined : result;
}
return isFalsy(data) ? undefined : data;
}
}
// removeEmptyValuesRecursively({a: { b: { d: {} } }) => undefined
// removeEmptyValuesRecursively({a: { b: { d: {} c: 1 } }) => {a : { b : { c: 1} } }
@jsunico
Copy link

jsunico commented Apr 1, 2022

Thanks for this @kra3. I tried this and made a small modification because I noticed that when there is a null value in an array, it will become:

[ <1 empty item>, { my: object } ]

And when converted into JSON, it just becomes null again because there is an empty element in the array. Instead of saving the next non-falsy value to the same index, I modified it so that it pushes the element into the array thereby eliminating empty elements.

          if (Array.isArray(res)) {
            res.push(newValue)
          } else {
            res[key] = newValue
          }

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