[英]Handlebars.js access nested array values by variable
I have a nested object, all indexes are timestamps and it contains information about the date of the timestamp and events on that day 我有一个嵌套的对象,所有索引都是时间戳,它包含有关时间戳日期和当天事件的信息
data : {
1522620000: {
events: {
1522620940: {title: event1},
1522620970: {title: event2},
}
},
1522706400:
events: {
1522620940: {title: event4},
1522620970: {title: event6},
}
},
1523311200: {
events: {}
},
...
}
How can I access all events on Friday without looping through the array? 如何在不循环访问数组的情况下访问星期五的所有事件? I only have the timestamp
1522706400
represented as the variable timestamp
and I would like to access it like data[timestamp].events
我只有时间戳
1522706400
表示为可变timestamp
,我data[timestamp].events
一样访问它
Currently I have 目前我有
{{#each day}} //<-- another variable from a calendar.. don't care about it
{{# each data[timestamp].events }} //<-- the day contains information about the timestamp but does not contain the events..
{{ title }}
{{/each}}
{{/each}}
I'm usually using AngularJS to accomplish things like that but I have a client that wants me to use handlebars instead and I'm really confused about it. 我通常使用AngularJS来完成类似的工作,但是我有一个客户端希望我改用车把,对此我感到很困惑。
I was able to solve it by myself. 我自己就能解决。 I created the following
Helper
我创建了以下
Helper
Handlebars.registerHelper("getNestedValue", function(obj, options) {
var context,
response = "";
var timestamp = options.hash.key;
if(typeof obj[timestamp] !== 'undefined'){
var data = obj[timestamp]; // <-- all information for the timestamp
$.each(data.events, function (index, item) { // <-- loop through all events
context = item;
response += options.fn(context); // <-- include the variable to the template
});
}
return response;
});
So I can access it like 所以我可以像访问它
{{#getNestedValue ../data key=timestamp }}
<li class="icon-calendar-events-16">
<a href="{{ url }}">
{{ title }}
</a>
<small>{{ location }}</small>
</li>
{{/getNestedValue}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.