gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 05:48:59 24 4
gpt4 key购买 nike

我正在尝试找出如何使用 _.countBy() 总结以下数据UnderscoreJS 中的方法.我有以下数据:

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 提供的方法?

最佳答案

尝试这个:

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/

关于underscore.js - 使用 .countBy 汇总数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12772645/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com