如何在javascript中检查对象中所有级别的对象是否为空

Jay*_*ani 4 javascript arrays json object is-empty

我想知道我的对象的所有嵌套对象和键值对是否为空。

例如,

const x = {
  a:"",
  b:[],
  c:{
    x:[]
  },
  d:{
    x:{
      y:{
        z:""
      }
    }
  }
};
Run Code Online (Sandbox Code Playgroud)

这应该是一个空对象,如果其中任何一个包含单个值,那么它应该是非空的。

Mah*_*Ali 7

这是使用递归执行操作的方法

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));
Run Code Online (Sandbox Code Playgroud)