[英]how to check if a certain key-value pair exists in array of hashes as json in ruby on rails
[英]How to group an array of hash by its value which has key-value pair in Ruby (Rails)?
所以我有以下 hash 數組:
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
方法按日期分組,但它沒有給出我想要的 output
我試過這種方法:
my_array.group_by { |element| element["date"] }.values
如果您只是想將輸入對象 1:1 映射到新形狀的 output object,那么您只需要使用Array#map
:
my_array.map {|entry| {entry["date"] => entry.except("date")} }
( Hash#except
來自 ActiveSupport,不是標准的 Ruby,但由於您在 Rails 中,它應該可以正常工作)。
兩種解決方案都假定關鍵"date"
是唯一的。 如果我們不能安全地做出這個假設,那么每個日期都應該映射到一個哈希數組。
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") }
試試這個
result = my_array.each_with_object({}) do |element, hash|
hash[element["date"]] = element.except("date")
end
puts result
我希望這有幫助: :)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.