Handlebars.js - variable as arrow key

34 Views Asked by At

I have JSON. I want to output an array element by a variable key. How can I do it? key is a variable.

{
  "key": 1,
  "last_request": {
    "items": [
      {
        "town": "London"
      },
      {
        "town": "Paris"
      },
      {
        "town": "Lisbon"
      }
    ]
  }
}

If I use {{last_request.items.[0].town}}, I have no problem. But {{last_request.items.[key].town}} is not working.

1

There are 1 best solutions below

0
76484 On BEST ANSWER

Handlebars has a built-in lookup helper for the purpose of getting a value from an object using a dynamic key. In your case, because the key is not the final property lookup, but town is, you would need to use lookup twice, in a nested fashion. The inner lookup would get the item at key and the outer lookup would get the town. The result would be:

{{lookup (lookup last_request.items key) 'town'}}

const template = Handlebars.compile(`{{lookup (lookup last_request.items key) 'town'}}`);

const data = {
  "key": 1,
  "last_request": {
    "items": [
      {
        "town": "London"
      },
      {
        "town": "Paris"
      },
      {
        "town": "Lisbon"
      }
    ]
  }
};

const output = template(data);

console.log(output);
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.7.8/handlebars.min.js"></script>