user1735921 user1735921 - 2 months ago 10
Ruby Question

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

I have long list of values in the inner_value field from which I want only some values

I have array in this format:

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


Desired Output:

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


I have tried using running loop in this but its too much costly.

So I tried something like this:

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


but this ain't working either..

Note:Order/Sort does not matter

Answer

Your aim is not to select, you have to modify the input:

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

Here you'd basically change the value of whole hash['inner_value'] to what you want.

To do this with known key:

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

For multiple keys:

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