Reputation: 13
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
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.
Upvotes: 0
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
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