userXYZ
userXYZ

Reputation: 50

How to check if array inside object is empty JavaScript

const isEmpty = Object.keys(data).every((key) => {
  return data[key].length === 0;
});

How can I check if all arrays in objects are empty. Problem with this code I tried is that I get this:

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

For first object I get false and that's okay but for the second I get true but I want to get false until all of arrays.length > 0, so I need to get true only for this situation:

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

Upvotes: 1

Views: 1084

Answers (3)

samuelcolt
samuelcolt

Reputation: 263

Use Object.values method.

Object.values(data).some(it => !it.length)

Upvotes: 1

Vince
Vince

Reputation: 869

The solution

function CheckArray(obj) {
  this.haveItems = false;

  this.onCheck = function (obj) {
    let createdArr = Object.values(obj);
    
    for (let i = 0; i < createdArr.length; i++) {
      if (createdArr[i].length > 0) {
        this.haveItems = true;
        break;
      }
    }
  };
}

let data = {
  0: [],
  1: [],
  2: [],
};

let a = new CheckArray();
a.onCheck(data);

console.log(a);

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386560

You could check the lenght of all values.

const isEmpty = data => !Object.values(data).every(({ length }) => length);

console.log(isEmpty({ 0: [], 1: [], 2: [] }));
console.log(isEmpty({ 0: [], 1: [1], 2: [] }));
console.log(isEmpty({ 0: [0], 1: [1], 2: [2] }));

Upvotes: 5

Related Questions