cris
cris

Reputation: 13

Convert hash of hash in array of hash

I need to modify a hash of hash and convert it in a hash of array.

I also need to add a new key value.

This is my current hash:

{ "132552" => {
           "name" => "Paul",
           "id" => 53
         },
"22478" => {
          "name" => "Peter",
           "id" => 55
        }
}

I expect the output to be like this:

[
  {
      "person_id": "132552",
      "name" => "Paul",
      "id" => 53
   },
   {
      "person_id": "22478",
      "name" => "Peter",
      "id" => 55
   }
]

Upvotes: 0

Views: 264

Answers (3)

colinux
colinux

Reputation: 4589

This is a perfect fit for Enumerable#each_with_object.

output = input.each_with_object([]) do |(person_id, values), array|
  array << values.merge("person_id" => person_id)
end

This method takes an arbitrary object for our initial state (here an array), iterate the collection (our hash) with a block. The initial object is yield as second argument of the block. At each iteration we're populating the array as we want. At the end of the block this object is returned, in output variable in my example.

Note that in my example, I destructure the hash into (person_id, values) : each entry of an hash can be destructed as (key, values) into block/method arguments.

Enumerable#each_with_object

Upvotes: 0

iGian
iGian

Reputation: 11193

You could map with Enumerable#map to hash values merging (Hash#merge) the new pairs:

original_hash.map { |k,v| v.merge({ "person_id" => k }) }
#=> [{"name"=>"Paul", "id"=>53, "person_id"=>"132552"}, {"name"=>"Peter", "id"=>55, "person_id"=>"22478"}]

Upvotes: 2

Maxence
Maxence

Reputation: 2339

Probably not the best solution but the following should work (considering h is your hash):

@h.each do |key,value|
  value["person_id"] = key
end

@array = []

@h.each do |key, value|
  @array << value
end

Upvotes: 0

Related Questions