我将首先简化它:
old_arr = [
{user_id: 3, purchase: {amount: 2, type_id:3, name:"chocolate"}},
{user_id: 4, purchase: {amount: 1, type_id:3, name: "chocolate"}},
{user_id: 5, purchase: {amount: 10, type_id:4, name: "penny-candy"}}]
intermediate_arr = old_arr.map{ |h| [h[:user_id], h[:purchase][:amount], h[:purchase][:type_id], h[:purchase][:name]]}
这将创建以下数组:
[[3, 2, 3, "chocolate"], [4, 1, 3, "chocolate"], [5, 10, 4, "penny-candy"]]
现在您可以按照自己的方式对其进行格式化。我选择这样格式化:
new_hash = {}
intermediate_arr.each do |arr|
if new_hash[arr[2]]
new_hash[arr[2]][:purchase] += [{user_id: arr[0], amount: arr[1]}]
else
new_hash[arr[2]] = {name: arr[3], purchase: [{user_id: arr[0], amount: arr[1]}]}
end
end
给予:
{3=>{:name=>"chocolate", :purchase=>[{:user_id=>3, :amount=>2}, {:user_id=>4, :amount=>1}]}, 4=>{:name=>"penny-candy", :purchase=>[{:user_id=>5, :amount=>10}]}}