handlebars.jsnested-loopsarrayiterator

Handlebars.js How to itarate through nested array using outer loop index


Hi. My JSON is:

variants : [
  {
    name : "one",
    segments : [
      { value : 1 },
      { value : 2 },
      { value : 3 }
    ]
  },
  {
    name : "two",
    segments : [
      { value : 4 },
      { value : 5 },
      { value : 6 }
    ]
  }
]

{{#each variants}}
  Index: {{@index}} 
  Value: {{segments.[@index].value}}
{{/each}}

I expect 1 and 5 for Value output. Index is not empty, but Value is empty. Why?


Solution

  • {{#each variants}}
      Index: {{@index}}
      {{#with (lookup segments @index}}
        {{value}}
      {{/with}}
    {{/each}}