Created
May 18, 2018 09:27
-
-
Save kra3/21239fca17b48283e42eca25bd45b51c to your computer and use it in GitHub Desktop.
remove false values from nested objects recursively
This file contains 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 _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} } } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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:
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.