Convert array of key value object to object of the key values (ruby)
2014-09-02 16:20
489 查看
I have a list of objects that have key attribute and value attribute.
I would like to convert it to an object that contains attributes named as keys with the values.
Example will make it clearer...
This
Should become like this:
I'm sure there is one line to make it happen Thanks
Using
I would like to convert it to an object that contains attributes named as keys with the values.
Example will make it clearer...
This
[{ :key => "key1", :value => "value1" }, { :key => "key2", :value => "value2" }]
Should become like this:
{ :key1 => "value1" :key2 => "value2" }
I'm sure there is one line to make it happen Thanks
Using
Hash::[],
Array#map:
a = [{ :key => "key1", :value => "value1" }, { :key => "key2", :value => "value2" }]
Hash[a.map { |h| [h[:key], h[:value]] }]
# => {"key1"=>"value1", "key2"=>"value2"}
Hash[a.map { |h| h.values_at(:key, :value) }]
# => {"key1"=>"value1", "key2"=>"value2"}
Hash[a.map { |h| [h[:key].to_sym, h[:value]] }]
# => {:key1=>"value1", :key2=>"value2"}
a.each_with_object({}) {|h,g| g.update({h[:key].to_sym => h[:value]}) }
# => {:key1=>"value1", :key2=>"value2"}
相关文章推荐
- How to combine the value of multiple hashes within an array by the same key
- ruby merge array of hashes based on the key and order it by number of key/value pair
- How to limit an array of similar hashes to those that have more than one of the same key:value pair
- How to sort a Map<Key, Value> on the values in Java?
- Err:The "." operator was supplied with an index value of type "java.lang.String" to be applied to a List or array
- How to sort an array of hashes into hashes with multiple values for a key?
- 1. MaxCounters 计数器 Calculate the values of counters after applying all alternating operations: increase counter by 1; set value of all counters to current maximum.
- Convert Array to Hash while preserving Array index values in Ruby
- Array.forEach() & Using square brackets to obtain the value of a property
- Ruby: how to sort array of string parsing the content
- Unable to get value of the property '2': object is null or undefined
- Array.forEach() & Using square brackets to obtain the value of a property
- Array.forEach() and Using square brackets to obtain the value of a property
- Cannot assign value of type 'AnyObject' to type 'HereIsTheTypeName?'
- System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException: Operation is not valid due to the current state of the obj
- Joining an array of keys to a hash with key value pairs like excel vlookup
- Whats the best way to split an array in ruby into multiple smaller arrays of random size
- The method below converts an array of objects to a DataTable object in C#.
- HOW TO CHANGE THE DEFAULT KEY-VALUE SEPARATOR OF A MAPREDUCE JOB
- convert the contents of an NSData object to an NSString