Created
May 18, 2018 09:27
-
-
Save kra3/21239fca17b48283e42eca25bd45b51c to your computer and use it in GitHub Desktop.
Revisions
-
kra3 created this gist
May 18, 2018 .There are no files selected for viewing
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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,34 @@ 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} } }