JavaScript SUM and GROUP BY of JSON data

后端 未结 5 1190
广开言路
广开言路 2020-12-02 13:46

This is my first attempt at doing JavaScript with some JSON data objects and need some advice on the proper way to attain my goal.

Some server-side code actually gen

5条回答
  •  再見小時候
    2020-12-02 14:10

    Given the dataString above, the below code seems to work. It goes through each object; if the category exists in the groupedObjects array, its hits and bytes are added to the existing object. Otherwise, it is considered new and added to the groupedObjects array.

    This solution makes use of underscore.js and jQuery

    Here's a jsfiddle demo: http://jsfiddle.net/R3p4c/2/

    var objects = $.parseJSON(dataString);
    var categories = new Array();
    var groupedObjects = new Array();
    var i = 0;
    
    _.each(objects,function(obj){
        var existingObj;
        if($.inArray(obj.category,categories) >= 0) {
            existingObj = _.find(objects,function(o){return o.category === obj.category; });
            existingObj.hits += obj.hits;
            existingObj.bytes += obj.bytes;
        } else {
            groupedObjects[i] = obj;
            categories[i] = obj.category;
            i++;
      }
    });
    
    groupedObjects = _.sortBy(groupedObjects,function(obj){ return obj.bytes; }).reverse();
    

提交回复
热议问题