8

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

2 Answers2

4

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'}
critrange
  • 5,652
  • 2
  • 16
  • 47
0

Here is another way with some details.

Needs/To keep in mind:

  1. getting within obj implies looping
  2. identify objects: avoid element not being object typed and only checks for object typed
  3. going deeper: for nested objects, a recursive pattern is handy.
    ( careful to avoid infinite loop w/ recursive function execution )
  4. delete/remove obj if empty

Code snippet:

 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 )
Laureline
  • 167
  • 4
  • 5