1

我有包含整个数据库记录的 json 数据,现在我需要对返回的 json 数据执行分组,并对特定类别进行排序。

我认为对 json 数据进行排序很容易,但我不确定如何使用 group by。我需要对特定的数据集进行分组。

任何帮助/建议都会有很大帮助。

谢谢拉维

4

3 回答 3

2
var obj = [{ "session":"1","page":"a"},
       { "session":"1","page":"b"},
       { "session":"1","page":"c"},
       { "session":"2","page":"d"},
       { "session":"2","page":"f"},
       { "session":"3","page":"a"}];

function GroupBy(myjson,attr){
    var sum ={};

    myjson.forEach( function(obj){
       if ( typeof sum[obj[attr]] == 'undefined') {
         sum[obj[attr]] = 1;
       }
       else {
         sum[obj[attr]]++;
       } 
    });
    return sum;
}

var result = GroupBy(obj,"page");

console.log("GroupBy:"+ JSON.stringify(result));
///  GroupBy(obj,"session")  --> GroupBy:{"1":3,"2":2,"3":1}
///  GroupBy(obj,"page")  --> GroupBy:{"a":2,"b":1,"c":1,"d":1,"f":1}
于 2012-08-17T13:11:27.807 回答
1

检查http://linqjs.codeplex.comhttp://jslinq.codeplex.com。它是模仿 LINQ 的 javascript 库。以下是与您类似的其他问题:Javascript 动态分组

于 2012-06-06T17:44:27.953 回答
0
    var obj = [{Poz:'F1',Cap:10},{Poz:'F1',Cap:5},{Poz:'F1',Cap:5},{Poz:'F2',Cap:20},{Poz:'F1',Cap:5},{Poz:'F1',Cap:15},{Poz:'F2',Cap:5},{Poz:'F3',Cap:5},{Poz:'F4',Cap:5},{Poz:'F1',Cap:5}];
Array.prototype.sumUnic = function(name, sumName){
    var returnArr = [];
    var obj = this;
    for(var x = 0; x<obj.length; x++){
        if((function(source){
            if(returnArr.length == 0){
                return true;
            }else{
                var isThere = [];
                for(var y = 0; y<returnArr.length; y++){
                    if(returnArr[y][name] == source[name]){
                        returnArr[y][sumName] = parseInt(returnArr[y][sumName]) + parseInt(source[sumName]);
                        return false;
                    }else{
                        isThere.push(source);
                    }
                }
                if(isThere.length>0)returnArr.push(source);
                return false;
            }
        })(obj[x])){
            returnArr.push(obj[x]);
        }
    }
    return returnArr;
}
obj.sumUnic('Poz','Cap');
// return "[{"Poz":"F1","Cap":45},{"Poz":"F2","Cap":25},{"Poz":"F3","Cap":5},{"Poz":"F4","Cap":5}]"
于 2014-06-09T21:39:41.927 回答