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
  • 2,069
  • 1
  • 23
  • 48
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
  • 7,373
  • 5
  • 31
  • 42
HBP
  • 15,685
  • 6
  • 28
  • 34
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
  • 81,153
  • 41
  • 202
  • 273