const object = { a: 1, b: { b1: 1, b2: 'a', b3: null, b4: undefined, b5: { b51: 1, b52: 'a', b53: null, b54: undefined, b55: '' } }, c: '' }; const expect = { a: 1, b: { b1: 1, b2: 'a', b5: { b51: 1, b52: 'a' } } }; function removeObjectBy(object, condition) { // lodash#cloneDeep const _obj = _.cloneDeep(object); const _cond = typeof condition === 'function' ? condition : function () {}; function _remove (obj) { for (let o in obj) { if (typeof obj[o] === 'object') { _remove(obj[o]); } if (_cond(obj[o])) { delete obj[o]; } } } _remove(_obj, _cond); return _obj; } const isEmpty = val => val === '' || val === null || val === undefined; const actual = removeObjectBy(object, isEmpty); document.getElementById('origin').innerText = JSON.stringify(object, null, 2); document.getElementById('expect').innerText = JSON.stringify(expect, null, 2); document.getElementById('result').innerText = JSON.stringify(actual, null, 2);
<pre id="origin"></pre> <pre id="expect"></pre> <pre id="result"></pre>