我怎么能数出某个东西在我的对象中出现了多少次

How can I count how many times something appears in my object?

本文关键字:对象 我的 多少次 怎么能      更新时间:2023-09-26

我需要查看一个代码在Customs键中出现的次数,然后在(名称:)下显示该代码以及在(数据:)中显示的次数。我想我已经接近了,请看下面的片段。因此,当我控制台日志数据时,我只想看到类似于-name:123213data: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]

我的版本与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] };
});

演示

这样就可以了。

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


参考:

  • 阵列.原型.减少
  • Object.keys
  • 了解JavaScript数组reduce