按照json的特定字段对数据进行分组,然后创建元素

时间:2016-10-17 17:55:42

标签: javascript jquery json

下面的代码是对数据进行分组并创建元素。但是缺少最后一组。我觉得我的循环很糟糕。

data:
        [
        {"GROUPID":"A","QTY":3,"STORE":"NYC"},
        {"GROUPID":"A","QTY":4,"STORE":"CT"},
        {"GROUPID":"B","QTY":2,"STORE":"NJ"},
        {"GROUPID":"B","QTY":5,"STORE":"NJ"},
        {"GROUPID":"C","QTY":1,"STORE":"MA"}
        ]

所以我的分组就像

NYC-3 NJ-4
B MA-1 CT - 4
C NJ-5

到目前为止,我的循环正在创建A组和B组但未创建组C. ..来自ajax

  success: function(msg) {
 var c = jQuery.parseJSON(msg.d);
 var myGroupid = c[0].GROUPID;
 var mList = "";
 var sum = "";

 for (var i = 0; i < c.length; i++) {
   currentGroup = c[i].GROUPID;
   if ((currentGroup !== myGroupid) {
       //compare if current record's group id is different than previous record.
       //if so, then means a new group. Send to plugin. 


       //call groupPlugin(myGroupid,mList)

     }
     mList += '<li'
     " data-group=" ' + c[i].GROUPID + '" data-store="' + c[i].STORE +'"</li>'

    }
}

1 个答案:

答案 0 :(得分:0)

我希望能正确理解你的问题。 我会这样:

groups = []; 
for (var i = 0; i < c.length; i++) {
    var groupID = c[i].GROUPID;
    if(groups[groupID]=="undefiend"){
       groups[groupID]=[];
    }
    groups[c[i].GROUPID].append(c[i]);
}

最后,您将拥有关联数组groups,其中包含由groupID

索引的所有组

然后得到一个组的所有元素(即A)

var group = groups["A"];
for (i=0;i<group.length;i++){
    console.log(group[i].STORE;    
}