2016-09-15 48 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"}}]