1

I have a list of items showing up on a page, using a struct. If a customer doesn't choose on of those items, I want to check if the struct is empty or not.

Here is my code:

shopItems.shopItemsStruct = {};

so when I do console.log(shopItems.shopItemsStruct) when I don't select a item, it shows me Object { }. How do I check in an if statement (ie if shop items are not selected)?

Thanks.

hkk
  • 1,929
  • 1
  • 19
  • 47
Udaan
  • 79
  • 1
  • 1
  • 10

2 Answers2

6

The function Object.keys returns an array of keys in the object it is passed as a parameter. If the returned value is zero then the object has no keys.

if (Object.keys(shopItems.shopItemsStruct).length === 0) {
    ...
}
ndugger
  • 6,366
  • 4
  • 26
  • 41
HBP
  • 14,098
  • 4
  • 25
  • 33
1

It is an object; a key value set. Just look for the presence of keys.

if( !Object.keys(shopItems.shopItemsStruct).length ){
 //no shop items selected                            
}
Travis J
  • 77,009
  • 39
  • 185
  • 250