计算JavaScript / NodeJS / Underscore中的散列值

我有一个ruby数组,看起来像这样:

domains = [ { "country" => "Germany"}, {"country" => "United Kingdom"}, {"country" => "Hungary"}, {"country" => "United States"}, {"country" => "France"}, {"country" => "Germany"}, {"country" => "Slovakia"}, {"country" => "Hungary"}, {"country" => "United States"}, {"country" => "Norway"}, {"country" => "Germany"}, {"country" => "United Kingdom"}, {"country" => "Hungary"}, {"country" => "United States"}, {"country" => "Norway"} ] 

编辑::

所以如果以这种格式(从CouchDB)返回:

 domains= {"total_rows":55717,"offset":0,"rows": [ {"country":"Germany"}, {"country":"United Kingdom"}, {"country":"Hungary"}, {"country":"United States"},\ \ {"country":"France"}, {"country":"Germany"}, {"country":"Slovakia"}, {"country":"Hungary"}, {"country":"United States"}, {"country":"Norway"}, {"country":"Germany"}, {"country":"United Kingdom"}, {"country":"Hungary"}, {"country":"United States"}, {"country":"Norway"}] } 

我怎样才能应用相同的过程。 即获取到embedded数组中的项目?

使用Ruby我可以在数组上进行交互,并删除重复的值,如下所示:

 counted = Hash.new(0) domains.each { |h| counted[h["country"]] += 1 } counted = Hash[counted.map {|k,v| [k,v.to_s] }] 

其输出如下所示:

 {"Germany"=>"3", "United Kingdom"=>"2", "Hungary"=>"3", "United States"=>"3", "France"=>"1", "Slovakia"=>"1", "Norway"=>"2"} 

我的问题是什么是最好的方式来实现相同的使用JavaScript可能使用像下划线库?

最好的祝福,

Carlskii

只是循环的值,并增加一个哈希计数。

 var count = {}; domains.forEach(function (obj) { var c = obj.country; count[c] = count[c] ? count[c] + 1 : 1; }); 

(请注意,IE 8及更早版本不支持forEach ,如果您关心它们,请使用polyfill或常规for循环)

你也可以像使用Ruby一样使用reduce函数:

 domains.reduce(function(country_with_count, country_object) { country_with_count[country_object['country']] = (country_with_count[country_object['country']] || 0) + 1; return country_with_count; }, {});