7

我试图弄清楚如何使用UnderscoreJS_.countBy()中的方法总结以下数据。我有以下数据:

var data =
[
    {"id":"338b79f07dfe8b3877b3aa41a5bb8a58","value":{"country":"United States"}},
    {"id":"338b79f07dfe8b3877b3aa41a5bb983e","value":{"country":"Norway"}},
    {"id":"338b79f07dfe8b3877b3aa41a5ddfefe","value":{"country":"Hungary"}},
    {"id":"338b79f07dfe8b3877b3aa41a5fe29d7","value":{"country":"United States"}},
    {"id":"b6ed02fb38d6506d7371c419751e8a14","value":{"country":"Germany"}},
    {"id":"b6ed02fb38d6506d7371c419753e20b6","value":{"country":"Hungary"}},
    {"id":"b6ed02fb38d6506d7371c419755f34ad","value":{"country":"United States"}},
    {"id":"b6ed02fb38d6506d7371c419755f3e17","value":{"country":"Germany"}},
    {"id":"338b79f07dfe8b3877b3aa41a506082f","value":{"country":"United Kingdom"}},
    {"id":"9366afb036bf8b63c9f45379bbe29509","value":{"country":"United Kingdom"}}
]

我想这样总结:

{ 
    United_States: 3,
    Norway: 1,
    Hungary: 2,
    Germany: 2,
    United_Kingdom: 2
}

我如何将它传递_.countBy()给 Underscore.js 提供的方法?

4

3 回答 3

15

试试这个:

var data =
[
    {"id":"338b79f07dfe8b3877b3aa41a5bb8a58","value":{"country":"United States"}},
    {"id":"338b79f07dfe8b3877b3aa41a5bb983e","value":{"country":"Norway"}},
    {"id":"338b79f07dfe8b3877b3aa41a5ddfefe","value":{"country":"Hungary"}},
    {"id":"338b79f07dfe8b3877b3aa41a5fe29d7","value":{"country":"United States"}},
    {"id":"b6ed02fb38d6506d7371c419751e8a14","value":{"country":"Germany"}},
    {"id":"b6ed02fb38d6506d7371c419753e20b6","value":{"country":"Hungary"}},
    {"id":"b6ed02fb38d6506d7371c419755f34ad","value":{"country":"United States"}},
    {"id":"b6ed02fb38d6506d7371c419755f3e17","value":{"country":"Germany"}},
    {"id":"338b79f07dfe8b3877b3aa41a506082f","value":{"country":"United Kingdom"}},
    {"id":"9366afb036bf8b63c9f45379bbe29509","value":{"country":"United Kingdom"}}
];

var countData = _.countBy(data, function(obj){
    return obj.value.country.replace(" ", "_");
}); 

console.log(countData);

JSFiddle:http: //jsfiddle.net/hyDv7/1/

于 2012-10-07T20:46:58.580 回答
1

“干净的js”:

var t = {};
for(var i = 0, l = data.length; i < l; i++){
    t[data[i].value.country] = !t[data[i].value.country] ? 1 : t[data[i].value.country] + 1;
}

结果:

Germany 2
Hungary 2
Norway 1
United Kingdom 2
United States 3
于 2015-10-03T02:32:33.657 回答
0

1 班轮使用减少

var countData = data.reduce(function (a, x) {a[x.country] = (a[x.country] ? a[x.country] : 0) + 1; return a;}, {});
于 2019-07-04T11:26:32.000 回答