0

这是我的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值,(例如有 3 type= CHEESE1K, UHT, and ESL in bulan= 4)

怎么做?

4

3 回答 3

2

您的 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/

于 2012-07-04T04:43:41.877 回答
1

首先,将 JSON 放入一个字符串中,否则您的示例代码将无法工作。

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":"2485​​3","type ":"WHP","uang":"386175022"}]}';6","total":"2485​​3","type":"WHP","uang":"386175022"}]}';6","total":"2485​​3","type":"WHP","uang":"386175022"}]}';

然后,迭代for并计算变量或哈希图。

由于GetReportIdResult是一个数组,您可以:

for( var i : obj.GetReportIdResult ){
    obj.GetReportIdResult[i] ... // Use at will.
于 2012-07-04T04:30:06.107 回答
1

这将为您提供一个map包含每个bulan值的计数的对象。例如,map['4'].count将返回 3。

var i, row, arr = obj.GetReportIdResult, map = {};
for (i = 0; i < arr.length; i++) {
    row = arr[i];
    map[row.bulan] = map[row.bulan] || {count: 0};
    if (map[row.bulan][row.type] === undefined) {
        map[row.bulan][row.type] = row.type;
        map[row.bulan]['count'] += 1;
    }
}
console.log (JSON.stringify(map));​

JSFiddle在这里

于 2012-07-04T04:46:14.700 回答