这是我的JavaScript:

var json = '{"GetReportIdResult":[{"bulan":"4","total":"1728","type":"CHEESE1K","uang":"8796383"},{"bulan":"4","total":"572476","type":"ESL","uang":"5863408410"},{"bulan":"4","total":"33507","type":"WHP","uang":"235653242"},{"bulan":"5","total":"4761","type":"CHEESE1K","uang":"134877865"},{"bulan":"5","total":"245867","type":"UHT","uang":"1446787280"},{"bulan":"5","total":"47974","type":"WHP","uang":"631929807"},{"bulan":"6","total":"5762","type":"CHEESE1K","uang":"293393832"},{"bulan":"6","total":"236803","type":"UHT","uang":"2219506085"},{"bulan":"6","total":"24853","type":"WHP","uang":"386175022"}]}';
obj = JSON.parse(json);
var arrayobj = obj.GetReportIdResult.length;
alert (arrayobj);


我想计算同一个type值中有多少bulan(例如,在type = 4中有3个CHEESE1K = UHTESLbulan

怎么做?

最佳答案

JSON中仍然有一个错字:在前两个"bulan":"6"对象之间连续有两个逗号。但是假设您解决了...

如果您要询问如何为特定的bulan值计算不同的类型,可以执行以下操作:

function countTypesForBulan(resultArray, bulanVal) {
   var i,
       types,
       count = 0;
   for (i=0, types = {}; i < resultArray.length; i++)
      if (resultArray[i].bulan === bulanVal && !types[resultArray[i].type]) {
         types[resultArray[i].type] = true;
         count++;
      }
   return count;
}

console.log( countTypesForBulan(obj.GetReportIdResult, "4") );  // logs 3


上面的代码循环遍历数组,以查找特定的bulan值,当找到一个值时,它会检查是否已经看到关联的类型-如果没有,则将其添加到types对象并增加计数器。

演示:http://jsfiddle.net/pAWrT/

07-23 04:46