-1

我想推入对象中的所有 0.0 值,所以我可以计算一个对象中有多少 0.0 值。到目前为止,我已经编写了一个代码来推送所有值(包括 0.0),但现在我只想推送0.0 VALUE
例如:
['cm_per1']2 个“0.0”,然后我想final_results['ESL']['cm_per1']在调用时推送它们final_results['ESL']['cm_per1'].length,它会显示“ 2 ”(因为有 2 个“0.0” cm_per1
这是我到目前为止所做的 >> 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);
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

您应该只需要更改这两行:

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 回答