How to remove all blank Objects from an Object in Javascript? Like this
const test={a:'a',b:{},c:{c:{}}}
How to get result:
test={a:'a'}
How to remove all blank Objects from an Object in Javascript? Like this
const test={a:'a',b:{},c:{c:{}}}
How to get result:
test={a:'a'}
The below recursive function will remove all empty objects.
function removeEmpty(obj) {
Object.keys(obj).forEach(k => {
if (obj[k] && typeof obj[k] === 'object' && removeEmpty(obj[k]) === null) {
delete obj[k];
}
});
if (!Object.keys(obj).length) {
return null;
}
}
Working Demo
function removeEmpty(obj) {
Object.keys(obj).forEach(k => {
if (obj[k] && typeof obj[k] === 'object' && removeEmpty(obj[k]) === null) {
delete obj[k];
}
});
if (!Object.keys(obj).length) {
return null;
}
}
const test1 = {data:{a:{}}};
removeEmpty(test1);
console.log(test1); // {}
const test2 = {data:{a:{}, b:1}};
removeEmpty(test2);
console.log(test2); // {data:{b: 1}}
const test3 = {a:'a',b:{},c:{c:{}}};
removeEmpty(test3);
console.log(test3); // {a: 'a'}
Here is another way with some details.
const test = {
a: "a", b: {},
c: { c: {} },
d: {
d: { e: {} }
},
}
function checkObjEmptiness(obj) {
// increases readability
// avoid "typeof" checking as "typeof [] === 'object' // returns true"
let isObject = (x) => x && x instanceof Object,
isEmpty = (x) => x && !Object.keys(x).length;
// 1. loops over obj to check each elements emptiness
for (let k in obj) {
// 2. check for object within object based on: isObject && !isEmpty
// 3. if object and not empty --> re-apply processus
if (isObject(obj[k]) && !isEmpty(obj[k])) checkObjEmptiness(obj[k]);
// handles deletion on obj if empty [ or value if empty ]
//if (isEmpty(obj[k]) || !obj[k]) delete obj[k]; // handles empty values
// 4. deletes object if empty
if (isEmpty(obj[k])) delete obj[k]; //handles empty object
}
return obj;
}
checkObjEmptiness( test )