How to remove all blank Objects from an Object in Javascript?

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'}

Tags:

Javascript