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} } }