2012-07-27 51 views
-1

我想推送對象中的所有0.0值,所以我可以計算一個對象中有多少個0.0值。到目前爲止,我已經創建了一個代碼來推送所有值(包括0.0),但現在我只想推只有0.0價值
例如:
['cm_per1']還有2「0.0」,然後我要推他們爲final_results['ESL']['cm_per1'],當我打電話final_results['ESL']['cm_per1'].length,它會顯示「」(因爲在cm_per1 2「0.0」)
這裏是我到目前爲止做出>>http://jsfiddle.net/xKJn8/26/如何將某個值推向數組?

var data = { 
    "MyData": [ 
    { 
     "cm_per1": "21.9", 
     "cm_per2": "31.8", 
     "tipe": "ESL" 
    }, 
    {  
     "cm_per1": "8.6", 
     "cm_per2": "7.0", 
     "tipe": "ESL" 
    }, 
    {  
     "cm_per1": "3.2", 
     "cm_per2": "0.0", 
     "tipe": "ESL" 
    }, 
    { 
     "cm_per1": "0.0", 
     "cm_per2": "0.0", 
     "tipe": "ESL" 
    }, 
    { 
     "cm_per1": "0.0", 
     "cm_per2": "0.0", 
     "tipe": "ESL" 
    } 
    ] 
}; 

var final_results = {}, 
    type, 
    current_row= ""; 
for (var i=0; i<data.MyData.length; i++) { 
    current_row = data.MyData[i]; 
    type = current_row.tipe; 

    //I want to count how many cm_per1 and cm_per2 that have 0.0 value  
    if (!final_results[type]) { 
      final_results[type] = { 
        "cm_per1": [], 
        "cm_per2": [] 
      }; 
    } 

    final_results[type].cm_per2.push(current_row.cm_per2); 
    final_results[type].cm_per1.push(current_row.cm_per1); 
} 
//but the result is it counts all cm_per1 and cm_per2, and what I need is only counts that have 0.0 value 
console.log(final_results['ESL']['cm_per1'].length); 

回答

1
var final_results = {}; 

data.MyData.forEach(function(o) { 
    // First check if it doesn't exist :-) 
    if (!final_results[ o.tipe ]) { 
     final_results[ o.tipe ] = { 
      "cm_per1": [], 
      "cm_per2": [] 
     }; 
    } 

    // Only push if the value is '0.0' 
    if (o.cm_per1 === '0.0') { 
     final_results[ o.tipe ][ 'cm_per1' ].push(o.cm_per1); 
    } 
    if (o.cm_per2 === '0.0') { 
     final_results[ o.tipe ][ 'cm_per2' ].push(o.cm_per2); 
    } 
}); 
console.log(final_results[ 'ESL' ][ 'cm_per1' ].length); // 2 
+0

但是,他希望2作爲一個結果,你的代碼顯示5! – 2012-07-27 07:34:35

+0

哦,猜我誤解了這個問題 – 2012-07-27 07:35:50

+0

謝謝你的回答:)但是.. 是的,我想得到2爲cm_per1和3爲cm_per2,然後我想它作爲數組,所以我可以稱它們爲長度。因爲該值將是動態的。你的第一個答案足夠接近我得到的東西,我只是把2個變量(count_1和count_2),但問題是我需要它作爲數組..這就是我迷惑 – blankon91 2012-07-27 07:39:11

1

你應該只需要更改這些兩行:

final_results[type].cm_per2.push(current_row.cm_per2); 
final_results[type].cm_per1.push(current_row.cm_per1); 

到:

if (current_row.cm_per2 === '0.0') { 
    final_results[type].cm_per2.push(current_row.cm_per2); 
} 
if (current_row.cm_per1 === '0.0') { 
    final_results[type].cm_per1.push(current_row.cm_per1); 
} 
+0

它也可以,謝謝爲答案:) – blankon91 2012-07-27 09:34:26