Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if object is empty in javascript for all levels in object

I wanted to find out if my object is empty or not for all its nested objects and key-value pairs.

for e.g.,

const x = {
  a:"",
  b:[],
  c:{
    x:[]
  },
  d:{
    x:{
      y:{
        z:""
      }
    }
  }
};

this should be an empty object and if any of this contains single value then it should be non empty.

like image 300
Jaydeep Galani Avatar asked Oct 31 '25 15:10

Jaydeep Galani


1 Answers

Here is the way to do what using recursion

const x = {
  a:"",
  b:[],
  c:{
    x:[]
  },
  d:{
    x:{
      y:{
        z:''
      }
    }
  }
};
function checkEmpty(obj){
  
  for(let key in obj){
    //if the value is 'object'
    if(obj[key] instanceof Object === true){
      if(checkEmpty(obj[key]) === false) return false;
    }
    //if value is string/number
    else{
      //if array or string have length is not 0.
      if(obj[key].length !== 0) return false;
    }
  }
  return true;
}
console.log(checkEmpty(x))
x.d.x.y.z = 0;
console.log(checkEmpty(x));
like image 95
Maheer Ali Avatar answered Nov 03 '25 05:11

Maheer Ali