如何检查对象中的数组是否全部为空? [英] How to Check if Arrays in a Object Are All Empty?

查看:102
本文介绍了如何检查对象中的数组是否全部为空?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我需要传递一个对象,其中每个属性都是数组。该函数将使用保存在每个数组中的信息,但是我想通过检查每个数组的每个数组是否为空/空来检查整个对象是否为空(不只是没有属性)。到目前为止,我所拥有的:

So I need to pass in a object where each of its properties are arrays. The function will use the information held in each array, but I want to check if the whole object is empty empty (not just having no properties) by checking if each of its arrays are empty/null as well. What I have so far:

function isUnPopulatedObject(obj) { // checks if any of the object's values are falsy
    if (!obj) {
        return true;
    }

    for (var i = 0; i < obj.length; i++) {
        console.log(obj[i]);
        if (obj[i].length != 0) {
            return false;
        }    
    }

    return true;  
}

因此,例如,这将导致上面的 false

So for example, this would result in the above being false:

obj {
    0: Array[0]
    1: Array[1]
    2: Array[0]
}

虽然这是我要检查的空白(确实如此):

While this is the empty I'm checking for (so is true):

obj {
    0: Array[0]
    1: Array[0]
    2: Array[0]
}

上面的代码不起作用。

The above code doesn't work. Thanks in advance.

推荐答案

因此,如果我们要遍历该对象并确定该对象的每个键是否都通过了检查,我们可以使用 Object.keys 和Array#extra every 这样,

So if we want to go through the object and find if every key of that object passes a check, we can use Object.keys and the Array#extra every like so:

var allEmpty = Object.keys(obj).every(function(key){
return obj[key].length === 0
})

这会将 allEmpty 设置为一个布尔值(真/假),具体取决于我们是否每次运行给定的检查 obj [key] .length === 0 是否返回真。

This will set allEmpty to a boolean value (true/false), depending on if every time we run the given check obj[key].length === 0 returns true or not.

此对象将 allEmpty 设置为true:

This object sets allEmpty to true:

var obj = {
    0: [],
    1: [],
    2: []
}

,而将其设置为false:

while this sets it to false:

var obj = {
    0: [],
    1: [],
    2: [],
    3: [1]
}

这篇关于如何检查对象中的数组是否全部为空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆