Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search for key-value from array of nested hash in ruby

I have array of nested hash that is,

@a = [{"id"=>"5", "head_id"=>nil,
         "children"=>
             [{"id"=>"19", "head_id"=>"5",
                 "children"=>
                     [{"id"=>"21", "head_id"=>"19", "children"=>[]}]},
             {"id"=>"20", "head_id"=>"5",
                 "children"=>
                     [{"id"=>"22", "head_id"=>"20", "children"=>[]}, {"id"=>"23"}]
             }]
     }]

I need array of all values which have key name 'id'. like @b = [5,19,21,20,22,23] I have already try this '@a.find { |h| h['id']}`. Is anyone know how to get this?

Thanks.

like image 277
rick Avatar asked Jan 09 '23 05:01

rick


1 Answers

You can create new method for Array class objects.

class Array
  def find_recursive_with arg, options = {}
    map do |e|
      first = e[arg]
      unless e[options[:nested]].blank?
        others = e[options[:nested]].find_recursive_with(arg, :nested => options[:nested])
      end
      [first] + (others || [])
    end.flatten.compact
  end
end

Using this method will be like

@a.find_recursive_with "id", :nested => "children"
like image 107
Nermin Avatar answered Jan 17 '23 22:01

Nermin