哈希数组到哈希的哈希

  • 本文关键字:哈希 数组 ruby
  • 更新时间 :
  • 英文 :


如何将哈希数组转换为response

response = [
{id: 1, name: 'foo', something: {}},
{id: 2, name: 'bar', something: {}}
]

其中:ids 是唯一的,将哈希transformed值作为response的元素,键作为相应的:id值转换为字符串,如下所示?

transformed = {
'1' => {id: 1, name: 'foo', something: {}},
'2' => {id: 2, name: 'bar', something: {}}
}

ruby 2.4.0起,您可以使用本机Hash#transform_values方法:

response
.group_by{|h| h[:id]}
.transform_keys(&:to_s)
.transform_values(&:first)
# => {
#      "1"=>{:id=>1, :name=>"foo", :something=>{}},
#      "2"=>{:id=>2, :name=>"bar", :something=>{}}
#    }

其他选项

response.map{ |i| [i[:id].to_s, i] }.to_h
#=> {"1"=>{:id=>1, :name=>"foo", :something=>{}}, "2"=>{:id=>2, :name=>"bar", :something=>{}}}
Hash[response.map{ |i| [i[:id].to_s, i] }]
#=> {"1"=>{:id=>1, :name=>"foo", :something=>{}}, "2"=>{:id=>2, :name=>"bar", :something=>{}}
response.inject({}) { |h, i| h[i[:id].to_s] = i; h }
#=> {"1"=>{:id=>1, :name=>"foo", :something=>{}}, "2"=>{:id=>2, :name=>"bar", :something=>{}}}

@Stefan的解决方案

response.each.with_object({}) { |i, h| h[i[:id].to_s] = i }
#=> {"1"=>{:id=>1, :name=>"foo", :something=>{}}, "2"=>{:id=>2, :name=>"bar", :something=>{}}}

@engineersmnky的解决方案

response.inject({}) {|h,i| h.merge({i[:id].to_s => i})} 
#=> {"1"=>{:id=>1, :name=>"foo", :something=>{}}, "2"=>{:id=>2, :name=>"bar", :something=>{}}}
response = [{ id: 1, name: 'foo', something: {} },{ id: 2, name: 'bar', something: { } }]    
hash = Hash.new    
response.each {|a| hash[a[:id].to_s] = a }
puts hash

如果将id作为结果哈希中的键,则无需再次将其保留在值中。使用each_with_object查看我的解决方案(从值中删除id(:

input
=> [{:id=>1, :name=>"foo", :something=>{}},
{:id=>2, :name=>"bar", :something=>{}}]
input.each_with_object({}) do |hash, out|
out[hash.delete(:id).to_s] = hash
end
=> {"1"=>{:name=>"foo", :something=>{}},
"2"=>{:name=>"bar", :something=>{}}}

注意:它将永久修改input数组。

但是,要获得问题中提到的确切输出,请执行以下操作:

input.each_with_object({}) do |hash, out|
out[hash[:id].to_s] = hash
end
=> {"1"=>{:id=>1, :name=>"foo", :something=>{}},
"2"=>{:id=>2, :name=>"bar", :something=>{}}}

最新更新