简体   繁体   中英

Ruby : Extract Key and Value from hash

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.

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"

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM