Reputation: 50
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
Reputation: 263
Use Object.values method.
Object.values(data).some(it => !it.length)
Upvotes: 1
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
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