{"name"=>"Package3", "price"=>3000.0, "id"=>"281"},"event_id"=>3-6ren">
gpt4 book ai didi

ruby - 考虑单个散列键值合并散列数组

转载 作者:太空宇宙 更新时间:2023-11-03 17:36:13 25 4
gpt4 key购买 nike

我有一个这样的哈希数组。

[
{"package_details"=>{"name"=>"Package3", "price"=>3000.0, "id"=>"281"},"event_id"=>336},
{"package_details"=>{"name"=>"2000/-", "price"=>2000.0, "id"=>"280"}, "event_id"=>337},
{"package_details"=>{"name"=>"Package1", "price"=>1000.0, "id"=>"282"},"event_id"=>337},
{"package_details"=>{"name"=>"Package2", "price"=>2000.0, "id"=>"283"},"event_id"=>337}
]

我希望它是这样的。

[
{"event_id"=>336, "package_details"=>[
{"name"=>"Package3", "price"=>3000.0, "id"=>"281"}
]},
{"event_id"=>337, "package_details"=>[
{"name"=>"2000/-", "price"=>2000.0, "id"=>"280"},
{"name"=>"Package1", "price"=>1000.0, "id"=>"282"},
{"name"=>"Package2", "price"=>2000.0, "id"=>"283"}
]},
]

Hash 应该根据相等的 event_id 值合并,并且 event 可以有很多包。

我想知道最简单的方法。尽管我能够处理很多 if 和 else 。

最佳答案

为您提供所需功能结果的最简单转换是使用 Enumerable#group_by .

details = [
{"package_details"=>{"name"=>"Package3","price"=>3000.0,"id"=>"281"},"event_id"=>336},
{"package_details"=>{"name"=>"2000/-","price"=>2000.0,"id"=>"280"},"event_id"=>337},
{"package_details"=>{"name"=>"Package1","price"=>1000.0,"id"=>"282"},"event_id"=>337},
{"package_details"=>{"name"=>"Package2","price"=>2000.0,"id"=>"283"},"event_id"=>337}
]

grouped = details.group_by{ |d| d["event_id"] }
#=> {
#=> 336=>[
#=> {"package_details"=>{"name"=>"Package3", "price"=>3000.0, "id"=>"281"}, "event_id"=>336}],
#=> 337=>[
#=> {"package_details"=>{"name"=>"2000/-", "price"=>2000.0, "id"=>"280"}, "event_id"=>337},
#=> {"package_details"=>{"name"=>"Package1", "price"=>1000.0, "id"=>"282"}, "event_id"=>337},
#=> {"package_details"=>{"name"=>"Package2", "price"=>2000.0, "id"=>"283"}, "event_id"=>337}]
#=> }

有了这个你就可以做到:

grouped.each do |event_id, packages|
# event_id is the actual value, like 336
# packages is an array of hashes from your original
end

如果您真的需要您描述的格式,那么您可以这样做:

transformed = details.group_by{ |d| d["event_id"] }.map do |event_id, hashes|
{
"event_id"=>event_id,
"package_details"=>hashes.map{ |h| h["package_details"] }
}
end
#=> [
#=> {"event_id"=>336, "package_details"=>[
#=> {"name"=>"Package3", "price"=>3000.0, "id"=>"281"}
#=> ]},
#=> {"event_id"=>337, "package_details"=>[
#=> {"name"=>"2000/-", "price"=>2000.0, "id"=>"280"},
#=> {"name"=>"Package1", "price"=>1000.0, "id"=>"282"},
#=> {"name"=>"Package2", "price"=>2000.0, "id"=>"283"}
#=> ]}
#=> ]

以上内容贯穿了分组并将每个键/值对转换(“映射”)为自定义哈希,其内容已根据您的需要进行了修改。

关于ruby - 考虑单个散列键值合并散列数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15596510/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com