Accessing an element within a list of Json objects using handlebars.js

254 Views Asked by At
"guests": [
    {
      "guestname": "john smith",
      "is_active": false,
      "guestheight": "175cm",
      "guestprofile": "https://www.example.com"
    },
    {
      "guestname": "david smart",
      "is_active": false,
      "guestheight": "175cm"
    }
  ]

I would like to check if guestprofile exist. Given that I currently have a variable holding the index of the list we are trying to access here, namely itemIndex. So basically I'm trying to query if guests[itemIndex]["guestprofile"] in handlebars.js context.

If I make a direct reference like

{{#if guests.0.guestprofile}}
  //do something
{{/if}}

its working fine. However, if I replace 0 with itemIndex like below, everything broke...

{{#if guests.itemIndex.guestprofile}}
  //do something
{{/if}}

Currently I have also tried

{{#if (lookup guests itemIndex).guestprofile}}
  //do something
{{/if}}
{{#if guests[itemIndex].guestprofile }}
  //do something
{{/if}}

None of them actually worked. Please help, Thank you in advance!

1

There are 1 best solutions below

0
On

You were so close with your lookup attempt.

The issue is that Handlebars does not allow you to chain a key onto a lookup subexpression as you are doing with (lookup guests itemIndex).guestprofile. It just doesn't resolve dynamic variables that way, which is the same reason why lookup has to be used instead of guests.itemIndex.guestprofile.

The part you missed is that you actually need two lookups - one to get the element of guests at itemIndex and the second to get the guestprofile of that element.

Your template needs to become:

{{#if (lookup (lookup guests itemIndex) 'guestprofile')}}
    do something
{{/if}}

I have created a fiddle for your reference.