如何在Ruby(Rails)中将一个有键值对的散列数组按值分组?

oknwwptz  于 2023-01-01  发布在  Ruby
关注(0)|答案(3)|浏览(86)

所以我有一个哈希数组:

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
xxb16uws

xxb16uws1#

如果您只是想将输入对象1:1Map到新形状的输出对象,则只需使用Array#map

my_array.map {|entry| {entry["date"] => entry.except("date")} }

Hash#except来自ActiveSupport,不是标准的Ruby,但由于您使用的是Rails,它应该可以正常工作)。

izj3ouym

izj3ouym2#

两种解决方案都假设密钥"date"是唯一的,如果我们不能安全地做出这个假设,那么每个日期都应该Map到一个哈希数组。

my_array.each_with_object({}) do |x, hsh|
  date = x["date"]
  hsh[date] ||= []
  hsh[date] << x.except("date")
end

结果:

{
  "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"}
  ]
}

或者您可能喜欢:

my_array
  .sort_by { |x| x["date"] }
  .group_by { |x| x["date"] }
  .transform_values { |x| x.except("date") }
e3bfsja2

e3bfsja23#

试试这个

result = my_array.each_with_object({}) do |element, hash|
 hash[element["date"]] = element.except("date")
end

puts result

希望这能有所帮助!:)

相关问题