How to Check if Arrays in a Object Are All Empty?

This question already has an answer here:

  • How do I loop through or enumerate a JavaScript object? 29 answers

  • 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
    })
    

    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.

    This object sets allEmpty to true:

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

    while this sets it to false:

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

    An object doesn't have a length property. There are several other ways to loop through an object's values, which you should be able to find.

    To check if a value is an array, you can use Array.isArray .

    For example:

    function objectIsEmpty(obj) {
        return Object.keys(obj).every(function(key) {
          var val = obj[key];  
          
          if (Array.isArray(val) && val.length === 0) {
            return true;
          }
          
          // Other rules go here:
          // ...
          
          return false;
        });
    };
    
    
    console.log(objectIsEmpty({ 0: [], 1: [], 2: [] }));
    console.log(objectIsEmpty({ 0: [], 1: [1], 2: [] }));

    it is not working since your object doesn't have length property.

    Try this simple one

    function isUnPopulatedObject(obj) { 
        return Object.keys( obj ).filter( function(key){
          return obj[ key ].length > 0;  //if any array has a property then filter will return this key.
        }).length == 0; //used == here since you want to check if all are empty
    }
    

    or use every

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

    or use some

    function isUnPopulatedObject(obj) { 
        return Object.keys( obj ).some( function(key){
          return obj[ key ].length > 0;  
        }) === false; 
    }
    
    链接地址: http://www.djcxy.com/p/28844.html

    上一篇: 查找本地网络中的所有IP地址

    下一篇: 如何检查对象中的数组是否全部为空?