Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to loop through array inside an array in handlebar with Node.js + express

I have JSON array as follows:

{outer:[
    {
      Key1:"ID001", 
      Key2:[
             {
               innerKey1:"Myval1",
               innerKey2:"Myvalue2"
             }
            ]
    }
]}

Now in my HTML file :

<div>
    {{#each outer}}
        <b>key1:</b> {{this.Key1}} <br/>
        {{#each this.Key2}}
           <b>InnerKey1:</b> {{this.innerKey1}} <br/>
        {{/each}}
    {{/each}}
</div>

But it not showing up any inner values. Could anyone please help how to loop on inner array objects (i.e Key2 above). Do I need to write a separate helper for this?

like image 446
Amol M Kulkarni Avatar asked Sep 03 '25 09:09

Amol M Kulkarni


1 Answers

You must choose between object or array interation:

{
  outer:[{
    Key1:"ID001", 
    Key2:{
      innerKey1:"Myvalue1",
      innerKey2:"Myvalue2"
    },
    Key3:[
      "Myvalue4",
      "Myvalue5"
    ]    
  }]
}

<div>
  {{#each outer}}
    key1: {{this.Key1}} <br/>
    {{#each this.Key2}}
      {{@key}}: {{this}}
    {{/each}} <br/>
    {{#each this.Key3}}
      {{@index}}: {{this}}
    {{/each}}
  {{/each}}
</div> 

outputs:

key1: ID001 
innerKey1: Myvalue1 innerKey2: Myvalue2 
0: Myvalue4 1: Myvalue5

http://codepen.io/rafaelcastrocouto/pen/qgrFE

like image 116
rafaelcastrocouto Avatar answered Sep 05 '25 00:09

rafaelcastrocouto