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

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

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

例如,

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

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

这是使用递归

的方法

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));

你可以像下面这样写一个递归函数。函数创建一个包含 2 个可能值 true 和 false 的集合。如果set的大小为1,值为false,表示对象为空

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

function isEmpty(o, r = new Set()) {
  for (let k in o) {
    if(typeof o[k] === "object") {
      if(Array.isArray(o[k])) r.add(!!o[k].length);
      else isEmpty(o[k],r);
    } else r.add(!(o[k] === "" || o[k] === undefined || o[k] === null));
  }
  return r;
}
let result = isEmpty(x);

console.log(result.has(false) && result.size == 1);

我将对此使用递归方法,我们遍历 object.keys() 并检查与键相关的每个值是否为空,如果该值是一个对象,我们更深入一层检查一下。

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

const x1 = [0,0,0];
const x2 = {0:0,1:0,2:0};

const isEmpty = (obj, empty=true) =>
{
    Object.keys(obj).forEach((key) =>
    {
        if (typeof obj[key] === "object")
            empty = isEmpty(obj[key], empty);
        else
            empty = empty && (obj[key].length === 0);
            
        // Return early if we detect empty here.
        
        if (!empty) return empty;
    });
    
    return empty;
}

console.log("original x: ", isEmpty(x));

x.a = "I'm not empty";

console.log("x after edit: ", isEmpty(x));
console.log("x1: ", isEmpty(x1));
console.log("x2: ", isEmpty(x2));

试试(我们这里用recursion, fat arrow, obj. keys, reduce, ternary operator and object checking

let isEmpty = o => o.constructor.name === "Object" ? 
  Object.keys(o).reduce((y,z)=> y&&isEmpty(o[z]) ,true) : o.length == 0;

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


let isEmpty = o => o.constructor.name === "Object" ? 
    Object.keys(o).reduce((y,z)=> y&&isEmpty(o[z]) ,true) : o.length == 0;
  


// Test
console.log(isEmpty(x));
x.d.x.y.z="Smile to life and life will smile to you";
console.log(isEmpty(x));