Reputation: 2567
I have an array of hashes that I'm having trouble with extracting the key
and value
. The array looks like:
data = [{"key"=>"Name", "value"=>"Jason"}, {"key"=>"Age", "value"=>"21"},
{"key"=>"last_name", "value"=>"bourne"}]
How can I convert this to the following array of hashes?
[{"Name"=>"Jason"}, {"Age"=>"21"}, {"last_name"=>"bourne"}]
I was able to use detect
:
a = d.detect { |x| x["key"] == "Name" }
puts a['value']
to get the value for "name"
, but would like to know if there is a better way.
Upvotes: 1
Views: 1767
Reputation: 110675
The calculation should not depend on the keys of the hashes, in case they are changed.
data.map { |h| [h.values].to_h }
#=> [{"Name"=>"Jason"}, {"Age"=>"21"}, {"last_name"=>"bourne"}]
Upvotes: 1
Reputation: 11807
I'd say that the most elegant way to go about this is probably to convert data
into a Hash first (assuming there are never any duplicate keys), like so:
data = data.map { |x| [x['key'], x['value']] }.to_h
# => {"Name"=>"Jason", "Age"=>"21", "last_name"=>"bourne"}
The #to_h
method expects each element of the array to be an array in the form [key, value]
, so the #map
call processes each element of data
to convert it into that form.
Once this has been done, you can simply access keys like any other hash:
data['Name'] # => "Jason"
data['Age'] # => "21"
Upvotes: 1