-1

我有一个 JSON 商店:

{
    "Week": 1145,
    "From": "IN1"
},
{
    "Week": 1145,       
    "From": "IN1"
},
{
    "Week": 1145,        
    "From": "IN2"
},
{
    "Week": 1146,
    "From": "IN1"
},
{
    "Week": 1146,
    "From": "IN2"
} 

我想为每个“周”计算“从”的数量,例如第 1146 周,我会得到 IN1 = 1 和 IN2 = 1,对于第 1145 周,我会得到 IN1 = 2 和 IN2 = 1。

我编写了一个函数,它遍历我的数据存储以计算每个参数的 IN1 和 IN2:

countBy: function(param){
    var count = {};
    this.each(function(item){
        var type = item.get(param);
        if (Ext.isDefined(count[type])){
            count[type]++;
        } else {
            count[type] = 1;
        }                               
    });
    return count;
}

但问题是当我在参数中给它“Week”时,它不计算每个WEEK的IN1和IN2,它返回“1145”:3和1146:2,但我想要的是:“1145”:{ IN1:2} 和“1146”:{IN1:1}。

感谢您的帮助!

4

1 回答 1

1

您也需要From作为参数传递。

试试下面:

countBy: function(param, param2){
    var count = {};
    this.each(function(item){
        var type = item.get(param);
        var from = item.get(param2);
        if (type in count){
            if (from in count[type]) {
              count[type][from]++;
            } else {
              count[type][from] = 1;
            } 
        } else {
            count[type] = {};
            count[type][from] = 1;
        }                               
    });
    return count;
}
于 2012-10-11T08:30:35.000 回答