JSON数据组

时间:2012-06-06 17:36:42

标签: javascript json

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

我认为排序很容易对json数据做,但我不知道我怎么能用group by。我需要分组特定的数据集。

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

由于 拉维

3 个答案:

答案 0 :(得分: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}

答案 1 :(得分:1)

检查http://linqjs.codeplex.comhttp://jslinq.codeplex.com。这是模仿LINQ的JavaScript库。以下是您的其他问题:Javascript Dynamic Grouping

答案 2 :(得分: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}]"