简体   繁体   English

把手 - 如何访问子数组的第一个元素?

[英]handlebars - how to access first element of child array?

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} 在我想要读出的示例中:{“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}}

In order to get the first element, you would need: 为了获得第一个元素,您需要:

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

but this would just print [object object]. 但这只会打印[object object]。

The second requirement - viewing it as JSON - requires a helper in your JS: 第二个要求 - 将其视为JSON - 需要JS中的帮助:

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

and then: 接着:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM