簡體   English   中英

Ruby on Rails數組格式化-從哈希數組內部的內部數組中刪除//選擇值

[英]Ruby on rails array formatting - removing//selecting values from inner array inside a hash array

我在inner_value字段中有很長的值列表,從中我只需要一些值

我有這種格式的數組:

hash_array = [
  {
    "array_value" => 1,
    "inner_value" => [
      {"iwantthis" => "forFirst"},
      {"iwantthis2" => "forFirst2"},
      {"Idontwantthis" => "some value"},
      {"iwantthis3" => "forFirst3"},
      {"Idontwantthis2" => "some value"},
      {"Idontwantthis3" => "some value"},
      {"Idontwantthis4" => "some value"},
      {"Idontwantthis5" => "some value"},
      {"Idontwantthis6" => "some value"},
    ]
  },
  {
    "array_value" => 2,
    "inner_value" => [
      {"iwantthis" => "forSecond"},
      {"Idontwantthis" => "some value"},
      {"iwantthis3" => "forSecond3"},
      {"iwantthis2" => "forSecond2"},
      {"Idontwantthis2" => "some value"},
      {"Idontwantthis3" => "some value"},
      {"Idontwantthis4" => "some value"},
      {"Idontwantthis5" => "some value"},
      {"Idontwantthis6" => "some value"},
    ]
  },
]

所需輸出:

[
  {
    "array_value" => 1,
    "inner_value" => [
      {"iwantthis" => "forFirst"},
      {"iwantthis2" => "forFirst2"},
      {"iwantthis3" => "forFirst3"}
    ]
  },
  {
    "array_value" => 2,
    "inner_value" => [
      {"iwantthis" => "forSecond"},
      {"iwantthis2" => "forSecond2"},
      {"iwantthis3" => "forSecond3"}
    ]
  },
]

我已經嘗試過在其中使用運行循環,但代價太高了。

所以我嘗試了這樣的事情:

hash_array.select { |x| x["inner_value"].select {|y| !y["iwantthis"].nil? } }

但這也不起作用..

注意:順序/排序無所謂

您的目標不是select ,而是必須修改輸入:

hash_array.map { |hash| hash['inner_value'] = hash['inner_value'].first }
#=> [
#     {
#       "array_value"=>1,
#       "inner_value"=> {
#          "iwantthis"=>"forFirst"
#        }
#      },
#      {
#        "array_value"=>2,
#        "inner_value"=> {
#          "iwantthis"=>"forSecond"
#        }
#      }
#    ]

在這里,您基本上將整個hash['inner_value']的值更改為所需的值。

為此,請使用已知密鑰:

hash_array.map do |hash|
  hash['inner_value'] = hash['inner_value'].find { |hash| hash['iwantthis'] }
end # `iwantthis` is the key, that can change

對於多個鍵:

keys = %w(iwantthis Idontwantthis)
hash_array.map do |hash|
  hash['inner_value'] = keys.flat_map do |key|
    hash['inner_value'].select {|hash| hash if hash[key] }
  end
end
#=> [{"array_value"=>1, "inner_value"=>[{"iwantthis"=>"forFirst"}, {"Idontwantthis"=>"some value"}]}, {"array_value"=>2, "inner_value"=>[{"iwantthis"=>"forSecond"}, {"Idontwantthis"=>"some value"}]}]

你可以用map

    hash_array.map{|k| {"array_value" => k['array_value'], 'inner_value' => k['inner_value'][0]} }

#=> [{"array_value"=>1, "inner_value"=>{"iwantthis"=>"forFirst"}}, {"array_value"=>2, "inner_value"=>{"iwantthis"=>"forSecond"}}]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM