javascript - 如何根据特定的 JSON 对象值对数组进行计数?

标签 javascript arrays json

这是我的 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/

关于javascript - 如何根据特定的 JSON 对象值对数组进行计数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11322388/

相关文章:

javascript - JSON 内的数组收到空

java - 我可以使用selenium网格在node.json中指定webdriver.gecko.driver吗?

javascript - JSON 对象作为键值对中的键

javascript - AngularJS 复选框无法正常工作

JavaScript: "TypeError: $(...).html(...).html(...).css is not a function"

java - 服务器发送事件 + Java 与 Spring MVC

javascript - 在 Web Push Notifications 中使用来自 Push 的数据

python - 将 numpy 数组保存到二进制文件

c - Top N 记录排序以仅返回排序数组中特定范围内的数字

javascript - mongo.db 更新可能有值或没有值的日期字段