如何将嵌套数组转换为散列或JSON,其值为数组

时间:2017-11-27 09:04:33

标签: arrays json ruby hash

我有这个嵌套数组

array = [["Colorado", "Adams County"], ["Colorado", "Jefferson County"], ["California", "Amador"], ["California", "Tulare"]]

我期待着这个

{"Colorado" => ["Adams County", "Jefferson County"], "California" => ["Amador", "Tulare"]}

我试过这些:

array.to_h
#=> {"Colorado"=>"Jefferson County", "California"=>"Tulare"}

b = Hash.new
array.uniq.map{|k,v| b[k] = v}
#=> {"Colorado"=>"Jefferson County", "California"=>"Tulare"}

array.uniq.map{|k,v| b[k] << v}
#=> Error

array.map{|k,v| b[k] = [v]}
#=> {"Colorado"=>["Jefferson CountyAdams CountyJefferson CountyAdams County"], "California"=>["TulareAmadorTulareAmador"]}`

如何将值作为数组获取?

2 个答案:

答案 0 :(得分:3)

您可以先调用group_by然后调用transform_values(Ruby 2.4 +):

hash = array.group_by(&:first)
# => {"Colorado"=>[["Colorado", "Adams County"], ["Colorado", "Jefferson County"]], "California"=>[["California", "Amador"], ["California", "Tulare"]]}
hash.transform_values! { |value_list| value_list.map(&:last) }
# => {"Colorado"=>["Adams County", "Jefferson County"], "California"=>["Amador", "Tulare"]}

如果你的红宝石没有transform_values,你可以map!

hash = array.group_by(&:first)
hash.each_value do |value_list|
  value_list.map!(&:last)
end
# => {"Colorado"=>["Adams County", "Jefferson County"], "California"=>["Amador", "Tulare"]}

答案 1 :(得分:1)

[["Colorado", "Adams County"], ["Colorado", "Jefferson County"],
 ["California", "Amador"], ["California", "Tulare"]].
   each_with_object(Hash.new { |h, k| h[k] = [] }) do |(k, v), h|
     h[k] << v
   end
#⇒ {
#  "California" => [
#    [0] "Amador",
#    [1] "Tulare"
#  ],
#    "Colorado" => [
#    [0] "Adams County",
#    [1] "Jefferson County"
#  ]
# }

或者,对于Ruby 2.4 +:

[["Colorado", "Adams County"], ["Colorado", "Jefferson County"], 
 ["California", "Amador"], ["California", "Tulare"]].
   group_by(&:shift).transform_values(&:flatten)