这是我的 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
= UHT
、 ESL
和 bulan
)
如何做到这一点?
最佳答案
您的 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
对象中,并增加计数器。
关于javascript - 如何根据特定的 JSON 对象值对数组进行计数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11322388/