1

How can I loop over and check if one or some arrays inside of a JavaScript Object is empty?

i.e.

const store = {
shirts : [],
shoes: ['nike', 'puma', 'addidas']
hats: [],
jerseys: ['barcelona', 'milan', 'arsenal']
}

5 Answers 5

2

Get the values of the object using Object.values(). Check if at least one of them is an array with the length of 0 using some and Array.isArray()

const store = {
  shirts: [],
  shoes: ['nike', 'puma', 'addidas'],
  hats: [],
  jerseys: ['barcelona', 'milan', 'arsenal']
}

console.log(
  Object.values(store).some(v => Array.isArray(v) && v.length === 0)
)

Sign up to request clarification or add additional context in comments.

Comments

2

If you just want to know whether there is an empty array, val will be true if one of the arrays is empty, otherwise false.

val = Object.keys(store).some(key => store[key].length === 0)

Comments

1

const store = {
shirts : [],
shoes: ['nike', 'puma', 'addidas'],
hats: [],
jerseys: ['barcelona', 'milan', 'arsenal']
}

for(let item in store){
  if(store[item].length == 0)
    console.log(item)
}


Each empty item will be logged to console

Comments

1

Here's a one liner:

const main = o => Object.entries(o).some(([k,a])=>!a.length);

console.log(
  main({x: [1,2,3],y: [123],}), // false
  main({x: [1,2,3],y: [],}), // true
  main({x: [],y: [],}), // true
);

Comments

1

If you want to get the empty keys than you can use filter method

const store = {
  shirts : [],
  shoes: ['nike', 'puma', 'addidas'],
  hats: [],
  jerseys: ['barcelona', 'milan', 'arsenal']
}

const emptyKeys = Object.keys(store).filter((key) => {
                     if (store[key].length == 0) { 
                       return key; 
                     } 
                   });

console.log(emptyKeys);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.