如何将对象数组转换为哈希数组?

时间:2015-02-09 04:23:24

标签: ruby arrays hash

我当前的对象数组“sum”是:

[{"sum":{"key1":0,"key2":"2014","key3":0,"key4":"8","key5":0,"key6":"0","key7":0}},
 {"sum":{"key1":0,"key2":"2014","key3":0,"key4":"12","key5":0,"key6":"1","key7":0}}]

目标是:

[{"key1":0,"key2":"2014","key3":0,"key4":"8","key5":0,"key6":"0","key7":0,
 {"key1":0,"key2":"2014","key3":0,"key4":"12","key5":0,"key6":"1","key7":0}]

2 个答案:

答案 0 :(得分:1)

使用Array#flat_map

array.flat_map(&:values)
# is same as :
array.flat_map { |hash| hash.values }
# or simply if you have
array.map { |hash| hash["sum"] }

答案 1 :(得分:0)

我使用了symbolize_keys @Muistooshort在本主题中提到的内容How to convert Object to array of hashes with symbol keys

所以,这是我使用的代码:

result = arr.map{|e| e.attributes.symbolize_keys}