在jQuery中使用Group by来汇总JSON数据

时间:2015-09-23 10:31:19

标签: jquery json

我正在获取以下数据。

var data =[{"Type1":2,"Type2":0,"Type3":6,"Date":"2015-01-27","Source":"Web"},
          {"Type1":2,"Type2":2,"Type3":0,"Date":"2015-02-27","Source":"Mobile"},
          {"Type1":3,"Type2":0,"Type3":7,"Date":"2015-02-27","Source":"Unknown"},
          {"Type1":4,"Type2":5,"Type3":9,"Date":"2015-02-27","Source":"Web"}]

我想通过像这样按日期分组来汇总这些数据,

var result= 
              [{"Type1":2,"Type2":0,"Type3":6,"Date":"2015-01-27"},
              {"Type1":9,"Type2":7,"Type3":16,"Date":"2015-02-27"}]

为此,我编写了以下jquery代码,但它不起作用。请建议我改变。

    var objects = JSON.stringify(data)
      var grphDates = new Array();
            var groupedObjects = new Array();
            $.each(objects, function (ix, obj) {
                var existingObj;
                if ($.inArray(obj.Date, grphDates) >= 0) {
                    existingObj = $.grep(groupedObjects, function (o, si) { return o.Date === obj.Date; });
                    existingObj.Type1 += obj.Type1;
                    existingObj.Type2 += obj.Type2;
                    existingObj.Type3 += obj.Type3;
                  } else {
                    groupedObjects.push(obj);
                    grphDates.push(obj.Date);
                }
            });

2 个答案:

答案 0 :(得分:1)

数据已经是一个对象数组,因此无需执行JSON.stringify(data)

还要考虑grep返回一个对象数组(http://api.jquery.com/jquery.grep/

这种改变应该这样做

      var data =[{"Type1":2,"Type2":0,"Type3":6,"Date":"2015-01-27","Source":"Web"},
          {"Type1":2,"Type2":2,"Type3":0,"Date":"2015-02-27","Source":"Mobile"},
          {"Type1":3,"Type2":0,"Type3":7,"Date":"2015-02-27","Source":"Unknown"},
          {"Type1":4,"Type2":5,"Type3":9,"Date":"2015-02-27","Source":"Web"}];

      var grphDates = new Array();
      var groupedObjects = new Array();
      $.each(data, function (ix, obj) {
           var existingObj;
           if ($.inArray(obj.Date, grphDates) >= 0) {
                // Get index of existing object width date == obj.Date
                var index = groupedObjects.map(function(o, i) { 
                               if(o.Date == obj.Date)return i;
                               }).filter(isFinite);

                groupedObjects[index].Type1 += obj.Type1;
                groupedObjects[index].Type2 += obj.Type2;
                groupedObjects[index].Type3 += obj.Type3;
           } else {
                groupedObjects.push(obj);
                grphDates.push(obj.Date);
           }
        });

答案 1 :(得分:0)

看一下使用lodash's groupBy method。它似乎几乎完全符合您的要求:

SPARK_LOCAL_IP

返回

_.groupBy(data, 'Date');