Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove empty object from JSON recursively using lodash

var template = {
    personal: {},
    education: {},
    certificate: [{"test": "Test"}, {}, {}],
    experience: []
}

removeEmptyObj(template);

function removeEmptyObj(obj)
for (var key in obj) {
    console.log("Foor Loop" + key + " " + obj[key]);
    if (_.isObject(obj[key]) && !_.isEmpty(obj[key])) {
        console.log("Second Loop Object:::" + key + " " + obj[key]);
        removeEmptyObj(obj[key]);
    }
    if (_.isEmpty(obj[key])) {
        console.log("Delete Object:::" + key + " " + obj[key]);
        obj = _.omitBy(obj, _.isEmpty);
    }
}
console.log(obj);
return obj;
}

Current Output is : {certificate: [{"test": "Test"}, {}, {}]}

Desired Output : {certificate: [{"test": "Test"}]}

What's wrong here your help appreciate :)

like image 713
Divyesh Kanzariya Avatar asked Jan 30 '23 03:01

Divyesh Kanzariya


1 Answers

You can _.transform() the object recursively to a new one, and clean empty objects and arrays on the way.

Note: I've added more elements to the structure for demonstration

var template = {
    personal: {},
    education: {},
    certificate: [{}, {"test": "Test"}, {}, {}, [{}], [{}, 1, []]],
    experience: [[1, 2, [], { 3: [] }]]
};

function clean(el) {
  function internalClean(el) {
    return _.transform(el, function(result, value, key) {
      var isCollection = _.isObject(value);
      var cleaned = isCollection ? internalClean(value) : value;

      if (isCollection && _.isEmpty(cleaned)) {
        return;
      }

      _.isArray(result) ? result.push(cleaned) : (result[key] = cleaned);
    });
  }

  return _.isObject(el) ? internalClean(el) : el;
}

console.log(clean(template));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
like image 153
Ori Drori Avatar answered Feb 02 '23 16:02

Ori Drori