Kevin Wang
Kevin Wang

Reputation: 3330

Handlebars.js - Access object value with a variable key

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?

Upvotes: 23

Views: 21578

Answers (2)

Mario Negrete
Mario Negrete

Reputation: 229

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

{{#each someArray}}
  {{lookup ../otherObject this}}
{{/each}}

Upvotes: 18

Fabricio c Zuardi
Fabricio c Zuardi

Reputation: 114

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]);
});

Upvotes: 5

Related Questions