我正在寻找迭代数组对象列表
这是我的示例对象
var Categories = {
"communication": [
{
"id": "communication_001",
"category": "communication",
"lastModified": "4 Day ago"
},
{
"id": "communication_002",
"category": "communication",
"lastModified": "1 Day ago"
}
],
"social": [
{
"id": "social_001",
"category": "social",
"lastModified": "2 Day ago"
}
],
"storage": [
{
"id": "storage_001",
"category": "storage",
"lastModified": "3 Day ago"
}
]
}
这里我正在使用车把
var render = Handlebars.compile(template)
render({ Categories : Categories })
那么我的编译模板是什么?
建议车把模板
答案 0 :(得分:1)
如果您确切知道要迭代哪个键,您可以尝试以下内容:
<div>
{{#each communication}}
<div>{{id}}</div>
<div>{{category}}</div>
<div>{{lastModified}}</div>
{{/each}}
{{#each social}}
<div>{{id}}</div>
<div>{{category}}</div>
<div>{{lastModified}}</div>
{{/each}}
{{#each category}}
<div>{{id}}</div>
<div>{{category}}</div>
<div>{{lastModified}}</div>
{{/each}}
</div>
否则,您可以尝试在 此 对象上使用双#each进行迭代,以访问所有子项并自动迭代键:
<div>
{{#each this}}
{{#each this}}
<div>{{id}}</div>
<div>{{category}}</div>
<div>{{lastModified}}</div>
{{/each}}
{{/each}}
</div>
希望这有帮助!
答案 1 :(得分:1)
您可以像对齐数组一样遍历对象。您不需要将数据包装在另一个对象中 - 只需参考this
。
var categories = {
"communication": [{
"id": "communication_001",
"category": "communication",
"lastModified": "4 days ago"
}, {
"id": "communication_002",
"category": "communication",
"lastModified": "1 day ago"
}
],
"social": [{
"id": "social_001",
"category": "social",
"lastModified": "2 days ago"
}],
"storage": [{
"id": "storage_001",
"category": "storage",
"lastModified": "3 days ago"
}]
};
var template = document.getElementById('template').innerHTML;
var render = Handlebars.compile(template);
document.getElementById('target-element').innerHTML = render(categories);
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.6/handlebars.min.js"></script>
<div id="target-element"></div>
<script id="template" type="text/x-handlebars-template">
<h1>Categories</h1>
{{#each this}}
<h2>{{@key}}</h2>
<ul>
{{#each this}}
<li><span>{{id}}</span> — <span>{{lastModified}}</span></li>
{{/each}}
</ul>
{{/each}}
</script>
&#13;