Galet
Galet

Reputation: 6269

How to get hash values from array

Input:-

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

sample_hash = {}

Function:-

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

Result:-

sample_hash

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

But i need expected result should be like below:-

sample_hash

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

How can i get my expected output?

Upvotes: 2

Views: 50

Answers (3)

jon snow
jon snow

Reputation: 3072

See this :

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"]}

Upvotes: 0

Arup Rakshit
Arup Rakshit

Reputation: 118261

@w0lf is correct. Same, but different construct.

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

Upvotes: 1

Cristian Lupascu
Cristian Lupascu

Reputation: 40506

You can initialize sample_hash using the new {|hash, key| block } Hash constructor to make the values in this hash be initialized to empty arrays by default. This makes it easier in the second phase, where each value in the initial data set is appended to the array of values indexed under the corresponding "name":

sample_hash = Hash.new { |h, k| h[k] = [] }
array.each { |f| sample_hash[f['name']] << f['value'] }

Try it online

Upvotes: 1

Related Questions