我如何计算物体出现的次数?

时间:2015-11-18 10:27:56

标签: javascript jquery json object

我需要查看代码出现在海关密钥中的次数,然后显示(名称:)下的代码以及它出现在(数据:)中的次数。我想我很接近请看下面的片段。因此,当我控制日志数据时,我想要看到的是 - name:123213 data: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]

2 个答案:

答案 0 :(得分:2)

我的版本与Rūdolfs非常相似,只是我使用map代替reduce来构建新数组。它还会检查Customs属性是否存在。

var out = arr.reduce(function (p, c) {
    if (c.Customs) {
        c.Customs.forEach(function (el) {
            p[el] = (p[el] || 0) + 1;
        });
    }
    return p;
}, {});

var out = Object.keys(out).map(function (key) {
  return { name: key, value: out[key] };
});

DEMO

答案 1 :(得分:1)

这应该这样做。

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);

供参考: