您的位置:首页 > 移动开发 > Objective-C

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
[{
: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"}


 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐