输入哈希数组是这样的:
[{count: 111, date: A},{count: 222, date: B},{count: 333, date: C}]
我想把它转换成:
{A => {count: 111}, B => {count: 222}, C => {count: 333}}
这只是一个简化版本,散列可能非常大 - 我的意思是很多键。
a = [{count: 111, date: 'A'},{count: 222, date: 'B'},{count: 333, date: 'C'}]
Hash[a.map {|h| [h[:date], {count: h[:count]}]}]
# => {"A"=>{:count=>111}, "B"=>{:count=>222}, "C"=>{:count=>333}}
aoh = [{count: 111, date: 'A'},{count: 222, date: 'B'},{count: 333, date: 'C'}]
flat = Hash[aoh.map {|h| [h.delete(:date), h]}]
# => {"A"=>{:count=>111}, "B"=>{:count=>222}, "C"=>{:count=>333}}
这与@falsetru 的解决方案类似,但更通用的是,如果原始哈希中除了:count
and之外还有更多键:date
,它们都将保留在结果中:
aoh = [{count: 111, date: 'A', pos: 1},{count: 222, date: 'B', pos: 2},{count: 333, date: 'C', pos: 3}]
flat = Hash[aoh.map {|h| [h.delete(:date), h]}]
# => {"A"=>{:count=>111, :pos=>1}, "B"=>{:count=>222, :pos=>2}, "C"=>{:count=>333, :pos=>3}}
该Array#inject
方法是一个不错的选择:
[{count: 111, date: 'A'},{count: 222, date: 'B'},{count: 333, date: 'C'}].inject({}) do |h, item|
h[item[:date]] = {count: item[:count]}
h
end