所以我有一个哈希数组:
my_array = [
{
"date" => "2022-12-01",
"pic" => "Jason",
"guard" => "Steven",
"front_desk" => "Emily"
},
{
"date" => "2022-12-02",
"pic" => "Gilbert",
"guard" => "Johnny",
"front_desk" => "Bella"
},
{
"date" => "2022-12-03",
"pic" => "Steven",
"guard" => "Gilbert",
"front_desk" => "Esmeralda"
}
]
我的问题是如何在Ruby(Rails 7)中按日期更改数组(分组)的结构,或者换句话说,我想将数组更改为如下形式:
my_array = [
{
"2022-12-01" => {
"pic" => "Jason",
"guard" => "Steven",
"front_desk" => "Emily"
{
},
{
"2022-12-02" => {
"pic" => "Gilbert",
"guard" => "Johnny",
"front_desk" => "Bella"
}
},
{
"2022-12-03" => {
"pic" => "Steven",
"guard" => "Gilbert",
"front_desk" => "Esmeralda"
}
}
]
不管怎样,先谢谢你的回答
我尝试过使用group_by
方法按日期分组,但它没有给予我想要的输出
我试过这个方法:
my_array.group_by { |element| element["date"] }.values
3条答案
按热度按时间xxb16uws1#
如果您只是想将输入对象1:1Map到新形状的输出对象,则只需使用
Array#map
:(
Hash#except
来自ActiveSupport,不是标准的Ruby,但由于您使用的是Rails,它应该可以正常工作)。izj3ouym2#
两种解决方案都假设密钥
"date"
是唯一的,如果我们不能安全地做出这个假设,那么每个日期都应该Map到一个哈希数组。结果:
或者您可能喜欢:
e3bfsja23#
试试这个
希望这能有所帮助!:)