我需要查看一个代码在“海关”键中出现多少次,然后在(name :)下显示该代码以及在(data :)中出现的次数。我想即时关闭,请参见下面的代码段。因此,当我管理日志数据时,我想看到的只是-名称:123213数据:22。

// Here is my json object
var json = [
    "G": "PIF",
    "H": "FOB",
    "I": "NINGBO",
    "J": "NGB",
    "K": "2014-10-01",
    "M": "2014-10-01",
    "Y": "LIVERPOOL",
    "zp": "LIV",
    "N": "2014-11-09",
    "P": "2014-11-09",
    "R": "2014-11-09T12:01",
    "V": true,
    "zk": " ",
    "zo": "7",
    "Customs": [
        "39210000"
    ],
    "LatLon": {}
},
//   ...... etc

// Here is my failed attempt
$(document).ready(function () {
    var CommodityCounts = {};
    var Commoditycds  = [];
    var totalCount    = 0;

    //loop through the object
    $.each(json, function(key, val) {
        var Commoditycd = val["Customs"];

        //build array of unique country names
        if ($.inArray(Commoditycd, Commoditycds) == -1) {
            Commoditycds.push(Commoditycd);
        }

        //add or increment a count for the country name
        if (typeof CommodityCounts[Commoditycd] == 'undefined') {
            CommodityCounts[Commoditycd] = 1;
        }
        else {
            CommodityCounts[Commoditycd]++;
        }

        //increment the total count so we can calculate %
        totalCount++;
    });

    //console.log(Commoditycds);
    var data = [];

    //loop through unique countries to build data for chart
    $.each(Commoditycds, function(key, Commoditycd) {
        data.push({
            name: Commoditycd,
            data: CommodityCounts
        });
    });
    console.log(data);
});

// Need the data to be show like (name of the code and how many times it appears in my json object-  name: '123123', data: [83]

最佳答案

这应该做。



var result = json.reduce(function(a, x) {
  x.Customs.forEach(function(c) {
    a[c] = a[c] ? a[c] + 1 : 1
  });
  return a;
}, {});

result = Object.keys(result).reduce(function(a, key) {
  return a.concat([{name: key, data: result[key]}])
}, []);

console.log(result);







以供参考:


Array.prototype.reduce
Object.keys
Understand JavaScript array reduce

关于javascript - 我如何计算物体中出现多少次?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33777545/

10-10 00:12