2012-10-11 72 views
-1

我有一個JSON店:如何計算每個參數的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每個PARAM功能:

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; 
} 

但問題是當我在param中給它「Week」時,它不會爲每個週期計入IN1和IN2,它會返回「114 5「:3和1146:2,但我想要的是:」1145「:{IN1:2}和」1146「:{IN1: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; 
} 
+0

謝謝,它的工作原理(也就是關閉parenthese後刪除(如果類型計數))。 你知道我怎樣才能把每個價值分開嗎?因爲我需要每週存儲IN1和IN2的總數,並使用它們繪製圖表。 我這樣做過: var countObject = myStore.countBy(「Week」,「From」); console.log(Ext.encode(countObject.IN2)) 得到IN2(我知道這非常天真,但我真的是新的extjs和JavaScript)。但它返回null。我想將它們存儲在變量中並在我的圖表中使用它們。提前致謝 – salamey