JSFiddle - React, Tailwind, and code Playground
JavaScript
const Utils = {
clean: function(object) {
const isEmptyObj = (obj) => Object.keys(obj).length === 0 && obj.constructor === Object;
const hasKeys = (obj) => Object.keys(obj).length > 0;
Object
.keys(object)
.forEach(key => {
const val = object[key];
if (!val || isEmptyObj(val)) {
delete object[key];
return object
} else if (Array.isArray(val)) {
let i = val.length;
while(i--) {
let entry = val[i];
if (!entry || isEmptyObj(entry)) {
val.splice(i, 1)
} else if (hasKeys(entry)) {
entry = Utils.clean(entry);
if (isEmptyObj(entry)) {
val.splice(i, 1)
}
}
}
if (val.length === 0) {
delete object[key];
}
}
});
return object;
}
}
console.log(JSON.stringify(Utils.clean({"a": [null,null,"b","c",{},{},{},{}]})));
// returns {"a":[null,"c",{},{},{}]}
// desired: {"a":["b", "c"]}
console.log(JSON.stringify(Utils.clean({"a": [null,null,"b","c",{"d": {}},{}]})));
// returns {"a":[null,"c",{},{}]}
// desired: {"a":["b", "c"]}
console.log(JSON.stringify(Utils.clean({ "a" : [null,null,{"d": {}, "e": [null, {}]},{}]})));
// returns {"a":[null,{}]}
// desired: {}