22

Looking for a way to access to achieve this:

{{#each someArray}}
  {{../otherObject.[this]}}
{{/each}}

How do I evaluate the value of this and then reference it as a key to my object otherObject?

Kevin Wang
  • 3,290
  • 1
  • 28
  • 40
  • 4
    I have, searched for 2 days. Maybe I'm just awful at googling. – Kevin Wang Oct 30 '13 at 02:44
  • 1
    [This one from the sidebar](http://stackoverflow.com/questions/18168924/how-to-get-an-array-value-at-index-using-handlebars-js?rq=1) is about 90% of the solution. Basically, you have to write our own helper that converts things like `{{value_at obj key}}` to the JavaScript `obj[key]`. – mu is too short Oct 30 '13 at 03:07
  • 3
    I've seen that answer, the second one refers to what I'm talking about, and I was hoping for a similar solution because it seems like such an obvious use case. It's hard to believe that handlebars doesn't support this syntax... – Kevin Wang Oct 31 '13 at 06:34
  • Did you find any workaround @KevinWang? I'm stuck on the same issue... – Mathieu Sep 25 '14 at 16:08

2 Answers2

19

With lookup: https://handlebarsjs.com/guide/builtin-helpers.html#lookup

{{#each someArray}}
  {{lookup ../otherObject this}}
{{/each}}
Community
  • 1
  • 1
Mario Negrete
  • 240
  • 2
  • 7
5

One possible solution with a helper:

/*
{{#each someArrayOfKeys}}
  {{#withItem ../otherObject key=this}}
    {{this}}
  {{/withItem}}
{{/each}}
*/

Handlebars.registerHelper('withItem', function(object, options) {
    return options.fn(object[options.hash.key]);
});