1

我在 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"}]
}

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

使用 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 可能使用下划线之类的库来实现相同目标的最佳方法是什么?

此致,

卡尔斯基

4

2 回答 2

1

只需循环这些值并在哈希中增加一个计数。

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

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

于 2012-10-06T09:32:11.420 回答
0

你也可以像在 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;
}, {});
于 2014-12-03T20:41:09.927 回答