您可以转换
obj.Cards
从映射到包含
id
和
data
最近
obj.Cards[id]
。这将允许您使用嵌套转发器。在这种情况下,您的代码可能是这样的:
JavaScript
function convert(obj) {
var data = [],
item,
id,
card,
i;
for(id in obj.Cards) {
if(obj.Cards.hasOwnProperty(id)) {
card = obj.Cards[id];
item = {
id: id,
data: []
};
for(i=0; i<card.length; i++) {
item.data.push( $.extend({},card[i]) );
}
data.push(item);
}
}
return {Cards: data};
}
var obj = {
"Cards":{
"Pack1":[{
"name":"John",
"color":"red"
}, {
"name":"Doe",
"color":"blue"
}],
"Pack2":[{
"name":"Smith",
"color":"green"
}]
}
};
var template = '{{#Cards}}' +
'<div>{{id}}</div>' +
'<ul>' +
'{{#data}}<li>{{name}}: {{color}}</li>{{/data}}' +
'</ul>' +
'{{/Cards}}';
var model = convert(obj);
$('body').append(Mustache.render(template, model));
JSBin:
http://jsbin.com/zujiqoyi/1/edit