-1

オブジェクト内のすべての0.0値をプッシュしたいので、オブジェクト内の0.0値の数を数えることができます。これまで、すべての値(0.0を含む)をプッシュするコードを作成しましたが、今は0.0VALUEのみをプッシュしたいと思います。
たとえば
['cm_per1']2つの「0.0」がある場合はプッシュしたいので、final_results['ESL']['cm_per1']呼び出すと「 2final_results['ESL']['cm_per1'].length 」と表示されます(に2つの「0.0」がある ため) これまでに作成したものです>> http://jsfiddle.net/xKJn8/26/cm_per1

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);
4

2 に答える 2

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
于 2012-07-27T07:33:44.437 に答える
1

次の2行を変更する必要があります。

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);
}
于 2012-07-27T07:45:13.883 に答える