给定JSON结果集,如下所示:
[ {fooID: 1, fooLabel: "one", barID: 20 barLabel: "twenty"},
{fooID: 1, fooLabel: "one", barID: 30 barLabel: "thirty"},
{fooID: 1, fooLabel: "one", barID: 40 barLabel: "forty"},
{fooID: 2, fooLabel: "two", barID: 500 barLabel: "fivehundred"},
{fooID: 2, fooLabel: "two", barID: 600 barLabel: "sixhundred"} ]
我怎么能在小组中迭代这个?
实施例
<legend>1 - one</legend>
<div>20 - twenty</div>
<div>30 - thirty</div>
<div>40 - forty</div>
<legend>2 - two</legend>
<div>500 - fivehundred</div>
<div>600 - sixhundred</div>
此外,最好是解决方案可以支持更多尺寸,甚至可能需要一些小的调整,因为看起来我将不得不在几个应用程序中使用它几次。它应该不是一个问题,但考虑到结果并不总是按照我提供的示例中的组顺序排列也可能是好的。可以订购1,2,2,1,2 ......等等。
答案 0 :(得分:1)
对数组进行排序,然后迭代并跟踪您所在的fooID
,并在更改时创建新图例。
var my_arr = [ {fooID: 1, fooLabel: "one", barID: 20, barLabel: "twenty"},
{fooID: 1, fooLabel: "one", barID: 30, barLabel: "thirty"},
{fooID: 1, fooLabel: "one", barID: 40, barLabel: "forty"},
{fooID: 2, fooLabel: "two", barID: 500, barLabel: "fivehundred"},
{fooID: 2, fooLabel: "two", barID: 600, barLabel: "sixhundred"} ];
my_arr.sort(function(a,b) {
return a.fooID > b.fooID;
});
var curr_group;
$.each(my_arr,function(i,v) {
if(curr_group !== v.fooID) {
curr_group = v.fooID;
$('<legend>',{text:v.fooID + ' - ' + v.fooLabel}).appendTo('body');
}
$('<div>',{text:v.barID + ' - ' + v.barLabel}).appendTo('body');
});