Search code examples
javascriptjqueryobjectis-empty

JS: Emptiness of Object of objects


How to check is empty object of objects?

The structure of object:

{
    order: [],
    search: [],
    where: {
        practices: [],
        role: [],
        status: []
    }
}


What I tried

$(object).length 

Returns 1

$.isEmptyObject(filterOptions)

Returns false


Solution

  • This isn't an empty object since it has three properties and the where property also has three nested properties.

    If you want to know if all the properties and nested properties are empty arrays then I would do this:

    var isEmpty = function(obj) {
      return Object.keys(obj).every(function(key) {
        if (Array.isArray(obj[key])) {
          return obj[key].length === 0;
        } else {
          return isEmpty(obj[key]);
        }
      })
    };
    
    var obj = {
      order: [],
      search: [],
      where: {
        practices: [],
        role: [],
        status: [],
        x: {
          y: {
            z: []
          }
        }
      }
    };
    
    console.log(isEmpty(obj));