Skip to content

Instantly share code, notes, and snippets.

@kra3
Created May 18, 2018 09:27
Show Gist options
  • Save kra3/21239fca17b48283e42eca25bd45b51c to your computer and use it in GitHub Desktop.
Save kra3/21239fca17b48283e42eca25bd45b51c to your computer and use it in GitHub Desktop.

Revisions

  1. kra3 created this gist May 18, 2018.
    34 changes: 34 additions & 0 deletions removeFalseValuesRecurse.js
    Original 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} } }