user1179321
user1179321

Reputation: 801

Looping through a multidimensional array in Handlebars.js

I have the server passing back this JSON and I'm not sure how to loop through a 2-dimensional array in Handlebars.

"userSurvey":[[1],[2],[3]]

I know to use {{#each userSurvey}} but then how would I go about do the arrays inside the usersurvey object?

Upvotes: 36

Views: 28065

Answers (4)

Sukrit Anand
Sukrit Anand

Reputation: 11

Use the #with helper for the obj

{ catg: [ 'java', 'c', 'c++' ],
  quesarray: [ [ 2, 1 ], [ 0, 2, 10, 5, 11, 12 ], [ 7, 5, 3, 8, 0 ] ],
  _id: 5d778d52d410984dc4e3e278,
  username: '[email protected]' }

if you want to access the array quesarray index wise do this

{{#each qset}}
{{#with quesarray}}
{{[2]}}
{{/with}}
{{/each}}

and output will be 7, 5, 3, 8, 0

Upvotes: 1

Dream Castle
Dream Castle

Reputation: 77

    {{#each Arr}}
        {{#each this}}
            <label>{{this.[0]}}</label> {{this.[1]}}<br>
        {{/each}}
    {{/each}}

Here is my simple example to loop array of my arrays :)

Upvotes: 0

Seva Arkhangelskiy
Seva Arkhangelskiy

Reputation: 685

In this particular case if you want to render just "123" you can do this:

{{#each userSurvey}}
    {{this.[0]}}
{{/each}}

Or even simpler, because arrays automatiaclly transform to strings:

{{#each userSurvey}}
    {{this}}
{{/each}}

Upvotes: 3

Simon Boudrias
Simon Boudrias

Reputation: 44589

You'd have to loop 2 times:

{{#each userSurvey}}
  {{#each this}}
    {{ this }}
  {{/each}}
{{/each}}

Upvotes: 77

Related Questions