我有一组嵌套的哈希:
[{"Group"=>"PR",
"Test1"=>{"Code"=>"100", " Price"=>"24.00", "AdditionalInfo"=>{"Cross"=>"true", "CrossId"=>"6"}},
"Test2"=>{"Code"=>"277", " Price"=>"12.00", "AdditionalInfo"=>{"Cross"=>"false"}}},
{"Group"=>"CO",
"Test1"=>{"Code"=>"45", " Price"=>"20.00", "AdditionalInfo"=>{"Cross"=>"true", "CrossId"=>"1"}},
"Test2"=>{"Code"=>"27", " Price"=>"15.00", "AdditionalInfo"=>{"Cross"=>"true", "CrossId"=>"2"}},
"Test6"=>{"Code"=>"131", " Price"=>"7.00", "AdditionalInfo"=>{"Cross"=>"false"}}},
{"Group"=>"OA",
"Test1"=>{"Code"=>"136", " Price"=>"14.00", "AdditionalInfo"=>{"Cross"=>"true", "CrossId"=>"7"}},
"Test2"=>{"Code"=>"18", " Price"=>"19.00", "AdditionalInfo"=>{"Cross"=>"true", "CrossId"=>"7"}},
"Test3"=>{"Code"=>"50", " Price"=>"8.00", "AdditionalInfo"=>{"Cross"=>"false"}},
"Test4"=>{"Code"=>"23", " Price"=>"3.00", "AdditionalInfo"=>{"Cross"=>"true", "CrossId"=>"8"}}}
]
我需要在数组中展平嵌套哈希并将其放在同一个数组中,如下所示。
[
{ "Group"=>"PR", "Code"=>"100", " Price"=>"24.00", "Cross"=>"true", "CrossId"=>"6" },
{ "Group"=>"PR", "Code"=>"277", " Price"=>"12.00", "Cross"=>"false" },
{ "Group"=>"CO", "Code"=>"45", " Price"=>"20.00", "Cross"=>"true", "CrossId"=>"1" },
{ "Group"=>"CO", "Code"=>"27", " Price"=>"15.00", "Cross"=>"true", "CrossId"=>"2" },
{ "Group"=>"CO", "Code"=>"131", " Price"=>"7.00", "Cross"=>"false" },
{ "Group"=>"OA", "Code"=>"136", " Price"=>"14.00", "Cross"=>"true", "CrossId"=>"7" },
{ "Group"=>"OA", "Code"=>"18", " Price"=>"19.00", "Cross"=>"true", "CrossId"=>"7" },
{ "Group"=>"OA", "Code"=>"50", " Price"=>"8.00", "Cross"=>"false" },
{ "Group"=>"OA", "Code"=>"23", " Price"=>"3.00", "Cross"=>"true", "CrossId"=>"8" }
]
任何人都可以帮忙!
答案 0 :(得分:3)
input.flat_map do |h|
# split the input into group and tests in the first place
h.partition { |k, v| k == "Group" }.reduce(&:product)
end.map do |(name, group), (_, data)|
# due to product above each element is a 2×2 array
# first item is the Group, the second is the TestN
{name => group}.merge(data.merge(data.delete("AdditionalInfo")))
end