A Mobin
A Mobin

Reputation: 148

How to check if Arrays inside Object are Empty

Here is my sample data. I want to check if Arrays inside an object are empty or not.

{
  collection: Array(0), 
  availability: Array(0), 
  gender: Array(0),
  brand: Array(0),
}

Following is the code that I am using right now (copied from some other stackoverflow link).

function objectIsEmpty(obj) {
    return Object.keys(obj).every(function(key) {
      var val = obj[key];  

      if (Array.isArray(val) && val.length === 0) {
        return true;
      }
      return false;
    });
}

Above code is working fine. My main question is there any cleaner way to check all empty arrays inside an Object through jQuery code like we use jQuery.isEmptyObject() to check the Empty object?

Thanks

Upvotes: 1

Views: 288

Answers (2)

CertainPerformance
CertainPerformance

Reputation: 370619

ES8 has Object.values, which is better than Object.keys if you just want the values. You can also directly return the Array.isArray(val) && val.length === 0 test, and concisely return if you want:

const objectIsEmpty = obj => Object.values(obj).every(
    val => Array.isArray(val) && val.length === 0
);

Upvotes: 6

Fraser
Fraser

Reputation: 17039

You don't need all the returns and assignments. e.g.

function objectIsEmpty(obj) {
    return Object.keys(obj).every(key => 
      Array.isArray(obj[key]) && obj[key].length;
    );
}

Upvotes: 2

Related Questions