Javascript 按多个属性对JSON结果集进行分组

Javascript 按多个属性对JSON结果集进行分组,javascript,jquery,ajax,json,iteration,Javascript,Jquery,Ajax,Json,Iteration,给定一个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:

给定一个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-one
20-20
30-30
40-40
2-2
500-500
600-600

此外,该解决方案最好能够支持更多维度,甚至可以进行一些小的调整,因为看起来我将不得不在多个应用程序中使用它几次。这不应该是一个问题,但考虑到结果并不总是按组排列,如我提供的示例中所示,这也可能是一件好事。它的顺序可能是1,2,2,1,2。。。等等。

对数组排序,然后迭代并跟踪您使用的
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');
});
var my_arr=[{fooID:1,傻瓜:“一”,barID:20,barLabel:“二十”},
{fooID:1,愚阿贝尔:“一”,巴里德:30,巴勒标签:“三十”},
{fooID:1,愚阿贝尔:“一”,巴里德:40,巴勒标签:“四十”},
{fooID:2,愚阿贝尔:“两个”,巴里德:500,酒吧标签:“五百”},
{fooID:2,愚阿贝尔:“两个”,巴里德:600,巴勒标签:“六百”};
我的数组排序(函数(a,b){
返回a.fooID>b.fooID;
});
var curr_组;
$。每个(我的arr,函数(i,v){
如果(当前组!==v.fooID){
curr_group=v.fooID;
$('',{text:v.fooID+'-'+v.doubabel}).appendTo('body');
}
$('',{text:v.barID+'-'+v.barLabel}).appendTo('body');
});

ooh!快点我想我可能已经弄明白了!这就是我想走的路线。我可能会接受你的回答,但我很想知道还有什么其他的可能。