admin管理员组

文章数量:1317904

I have an data object, which contains an array within an array, I want to loop over the parent array and read out the first object of each child array.

In the example I want to read out: {"id":1}, {"id":9}, {"id":11}

var object = 
{ parts: [ [{"id":1},{"id":2},{"id":3}], [{"id":9},...], [{"id":11},... ] ] }

so far I have a for each loop:

        {{#each object.parts}} ...  {{/each}}

I have an data object, which contains an array within an array, I want to loop over the parent array and read out the first object of each child array.

In the example I want to read out: {"id":1}, {"id":9}, {"id":11}

var object = 
{ parts: [ [{"id":1},{"id":2},{"id":3}], [{"id":9},...], [{"id":11},... ] ] }

so far I have a for each loop:

        {{#each object.parts}} ...  {{/each}}
Share Improve this question asked Feb 21, 2014 at 17:10 user3260177user3260177 1132 silver badges7 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 8

In order to get the first element, you would need:

{{#each object.parts}}
    {{this.[0]}}
{{/each}}

but this would just print [object object].

The second requirement - viewing it as JSON - requires a helper in your JS:

Handlebars.registerHelper('json', function(context) {
    return JSON.stringify(context);
});

and then:

{{#each object.parts}}
    {{json this.[0]}}
{{/each}}

本文标签: javascripthandlebarshow to access first element of child arrayStack Overflow