Search code examples
arraysindexinghandlebars.js

How to access an element from an array based on the other arrays index in handlebars?


I am currently having trouble accessing an element of an array based on the index of another array. Here is what I'm trying to do in a simplified version:

So I have 2 arrays that I pass to handlebars:

array1 = [Top, Mid, Jungle, ADC, Support]
array2 = [Gankplank, Ahri, Khazix, Ezreal, Janna]

Here is my simplified handlebars code:

{{#each array1}}
   {{this}} - {{array2.[@INDEX OF ARRAY 1]}}
{{/each}}

So my desired output would look like:

Top - Gankplank
Mid - Ahri
Jungle - Khazix
ADC - Ezreal
Support - Janna


Solution

  • Try the below snippets to create object and pass this object to handlebar template.

    In Underscore

    var tplObj = _.object(['Top', 'Mid', 'Jungle'], ['Gankplank', 'Ahri', 'Khazix']);
    // output => {'Top': 'Gankplank', 'Mid': 'Ahri', 'Jungle': 'Khazix'}
    

    In Plain JS

    var tplObj = {};
    for(var i in array1) {
     tplObj[ array2[i] ] = array1[i];
    }
    

    Iterate Object in handlebar template like below

    {{#each tplObj}}
        Key: {{@key}} Value = {{this}}
    {{/each}}