简体   繁体   中英

Convert Ruby array of hashes into one hash

I have the following array:

array = [{"a" => 2}, {"b" => 3}, {"a" => nil}, {"c" => 2}, {"b" => nil}]

I want to convert it into 1 big hash but keep all of the values, so I want it to look like the following:

{"a" => [2, nil], "b" => [3, nil], "c" => [2]}

I can get close doing array.inject({}) {|s, h| s.merge(h)}} array.inject({}) {|s, h| s.merge(h)}} , but it overwrites the values.

array = [{"a" => 2}, {"b" => 3}, {"a" => nil}, {"c" => 2}, {"b" => nil}]
a = array.each_with_object(Hash.new([])) do |h1,h|
  h1.each{|k,v| h[k] = h[k] + [v]}
end
a # => {"a"=>[2, nil], "b"=>[3, nil], "c"=>[2]}
array = [{"a" => 2}, {"b" => 3}, {"a" => nil}, {"c" => 2}, {"b" => nil}]
res = {}

array.each do |hash|
  hash.each do |k, v|
    res[k] ||= []
    res[k] << v
  end
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM