underscore.js – 使用.countBy汇总数据

前端之家收集整理的这篇文章主要介绍了underscore.js – 使用.countBy汇总数据前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试弄清楚如何使用 UnderscoreJS中的 _.countBy()方法汇总以下数据.我有以下数据:
var data =
[
    {"id":"338b79f07dfe8b3877b3aa41a5bb8a58","value":{"country":"United States"}},{"id":"338b79f07dfe8b3877b3aa41a5bb983e","value":{"country":"Norway"}},{"id":"338b79f07dfe8b3877b3aa41a5ddfefe","value":{"country":"Hungary"}},{"id":"338b79f07dfe8b3877b3aa41a5fe29d7",{"id":"b6ed02fb38d6506d7371c419751e8a14","value":{"country":"Germany"}},{"id":"b6ed02fb38d6506d7371c419753e20b6",{"id":"b6ed02fb38d6506d7371c419755f34ad",{"id":"b6ed02fb38d6506d7371c419755f3e17",{"id":"338b79f07dfe8b3877b3aa41a506082f","value":{"country":"United Kingdom"}},{"id":"9366afb036bf8b63c9f45379bbe29509","value":{"country":"United Kingdom"}}
]

我想这样总结一下:

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

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

解决方法

试试这个:
var data =
[
    {"id":"338b79f07dfe8b3877b3aa41a5bb8a58","value":{"country":"United Kingdom"}}
];

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

console.log(countData);

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

原文链接:https://www.f2er.com/js/155972.html

猜你在找的JavaScript相关文章