2016-09-15 55 views
0

我在inner_value字段值的長列表,從中我想僅一些值Ruby on Rails的陣列格式 - 除去//選擇哈希數組內從內陣列值

我有陣列的格式如下:

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? } } 

,但是這不工作或者..

注:訂單/排序不要緊

回答

2

你的目標是不是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"}]}] 
+0

你沒有。首先,我是說如果有什麼索引未知,但關鍵是已知的? – user1735921

+0

@ user1735921讓我更新使用已知的密鑰 –

+0

好吧,如果它的多個值,如假設有「iwanthis2」和「iwantthis3」 – user1735921

0

可以使用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"}}]