Reputation: 9
I am trying to convert an array of hashes into a hash with key as one of the elements of hash in the array.
For example: a = [{"active_accounts": 3, "id": 5}, {"active_accounts": 6, "id": 1}
I want to convert this array to
a = {5: {"active_accounts": 3}, 1: {"active_accounts": 6}}
I have tried doing it by looping over the array and accessing individual hash for a particular key but that doesn't seem to work. Any leads would be appreciated.
Upvotes: 0
Views: 236
Reputation: 4440
One more possible solution)
a.map { |hash| [hash.delete(:id), hash] }.to_h
#=> {5=>{:active_accounts=>3}, 1=>{:active_accounts=>6}}
Upvotes: 1
Reputation: 81
a.each_with_object({}) {|obj , hash| hash.merge!(Hash[obj[:id], Hash["active_accounts",obj[:active_accounts]]])}
# {5=>{"active_accounts"=>3}, 1=>{"active_accounts"=>6}}
Hope it helps.
Upvotes: 2
Reputation: 121000
Safe variant, mapping to arrays (same "id"
are expected and treated properly):
a.group_by { |e| e.delete("id") }
Exactly what you asked:
a.group_by { |e| e.delete("id") }
.map { |k, v| [k, v.first] }
.to_h
Upvotes: 1