如何从特定的JSON对象值计算数组?

时间:2012-07-04 04:24:18

标签: 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的数量{(1}},例如有3 type = CHEESE1KUHT和{{ 1}}在ESL = 4)

怎么做?

3 个答案:

答案 0 :(得分: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/

答案 1 :(得分:1)

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

var json ='{“GetReportIdResult”:[{“bulan”:“4”,“total”:“1728”,“type”:“CHEESE1K”,“uang”:“8796383”},{“bulan “:” 4" , “总”: “572476”, “类型”: “ESL”, “uang”: “5863408410”},{ “布兰”: “4”, “总”: “33507”,“类型“:” WHP”, “uang”: “235653242”},{ “布兰”: “5”, “总”: “4761”, “类型”: “CHEESE1K”, “uang”: “134877865”},{ “布兰”: “5”, “总”: “245867”, “类型”: “UHT”, “uang”: “1446787280”},{ “布兰”: “5”, “总”: “47974”, “类型”: “WHP”, “uang”: “631929807”},{ “布兰”: “6”, “总”: “5762”, “类型”: “CHEESE1K”, “uang”: “293393832”} ,, { “布兰”: “6”, “总”: “236803”, “类型”: “UHT”, “uang”: “2219506085”},{ “布兰”: “6”, “总”:” 24853" , “类型”: “WHP”, “uang”: “386175022”}]}';

然后, 使用for进行迭代并计入变量或散列映射。

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

for( var i : obj.GetReportIdResult ){
    obj.GetReportIdResult[i] ... // Use at will.

答案 2 :(得分: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 here