Reputation: 23
I try to merge some object into one array
I did output by
q = [["99","99","99"],["9"]]
o = [["b","1"],["c","3"],["d","1"],["c","30"]]
puts q.zip(o).map { |k,v| [*k,v] }.to_json
=> [["99",["b","1"]],["99",["c","3"]],["99",["d","1"]],["9",["c","30"]]]
i'm looking for best way to
[{"99"=>{"b"=>"1", "c"=>"3", "d"=>"1"}},{"9"=>{"c"=>"30"}]
Upvotes: 0
Views: 101
Reputation: 168111
a = [["9",["b","8"]],["9",["c","2"]],["9",["d","6"]]]
a.group_by(&:first).transform_values{|a| a.map(&:last).to_h}
# => {"9"=>{"b"=>"8", "c"=>"2", "d"=>"6"}}
a.group_by(&:first).transform_values{|a| a.map(&:last).to_h}.map{|k, v| {k => v}}
# => [{"9"=>{"b"=>"8", "c"=>"2", "d"=>"6"}}]
Upvotes: 1
Reputation: 16002
Looking for something like this?:
some_array = [["9",["b","8"]], ["9",["c","2"]], ["9",["d","6"]]]
some_hash = some_array.each_with_object(Hash.new{ |h,k| h[k] = {} }) do |(k, (sub_key, sub_val)), hash|
hash[k][sub_key] = sub_val
end
p some_hash
#=> {"9"=>{"b"=>"8", "c"=>"2", "d"=>"6"}}
Upvotes: 1