如何从数组中获取哈希值

How to get hash values from array

输入:-

array = [{"name"=>"id", "value"=>"123"}, 
         {"name"=>"type", "value"=>"app"}, 
         {"name"=>"codes", "value"=>"12"}, 
         {"name"=>"codes", "value"=>"345"}, 
         {"name"=>"type", "value"=>"app1"}] 

sample_hash = {}

函数:-

array.map {|f| sample_hash[f["name"]] = sample_hash[f["value"]] }

结果:-

sample_hash

 => {"id"=>"123", "type"=>"app", "codes"=>"345"} 

但我需要的预期结果应该如下所示:-

sample_hash

 => {"id"=>"123", "type"=>["app","app1"], "codes"=>["12", "345"]} 

如何获得预期的输出?

您可以使用 new {|hash, key| block } 哈希构造函数初始化 sample_hash,使此哈希中的值默认初始化为空数组。 这使得第二阶段变得更容易,其中初始数据集中的每个值都附加到相应 "name":

下索引的值数组中
sample_hash = Hash.new { |h, k| h[k] = [] }
array.each { |f| sample_hash[f['name']] << f['value'] }

Try it online

@w0lf 是正确的。相同,但构造不同。

array.each_with_object({}) do |input_hash, result_hash|
  (result_hash[input_hash['name']] ||= []) << input_hash['value']
end

看到这个:

array.inject({}) do |ret, a| 
    ret[a['name']] = ret[a['name']] ? [ret[a['name']], a['value']] : a['value']  
    ret
end

o/p : {"id"=>"123", "type"=>["app", "app1"], "codes"=>["12", "345"]}