Skip to content

Instantly share code, notes, and snippets.

@kevinguto
Forked from riston/remove.js
Created December 12, 2022 15:21
Show Gist options
  • Save kevinguto/05113496a70d71ea2f0d95046440a98c to your computer and use it in GitHub Desktop.
Save kevinguto/05113496a70d71ea2f0d95046440a98c to your computer and use it in GitHub Desktop.
Remove empty objects from object, recursive
var removeEmpty = function(object) {
if (!_.isObject(object)) {
return;
}
_.keys(object).forEach(function(key) {
var localObj = object[key];
if (_.isObject(localObj)) {
if (_.isEmpty(localObj)) {
delete object[key];
return;
}
// Is object, recursive call
removeEmpty(localObj);
if (_.isEmpty(localObj)) {
delete object[key];
return;
}
}
});
};
var a = {a: 1,b: [1, 2, 3, 4],c: {}};
removeEmpty(a);
console.log(a);
var b = [1, 2, 3, 4, {a: 1}];
removeEmpty(b);
console.log(b);
var c = {what: {data: {}},}; // you remove the data but what also remains empty
removeEmpty(c);
console.log(c); // the c should be empty object {}
var d = {what: {data: {tags: {remove: 1}}}}; // you remove the data but what also remains empty
removeEmpty(d);
console.log(d); // the c should be empty object {}
var e = {
what: {
board_data: {}
},
where: { }
};
removeEmpty(e);
console.log('e', e);
var f = { };
removeEmpty(f);
console.log('f', f);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment