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 :)
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With