简体   繁体   中英

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.

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"

It can be done like this, using recursion

def traverse_hash
  values = []
  @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"}]
         }]
 }] 
 get_values(@a)
end

def get_values(array)   
  array.each do |hash|        
    hash.each do |key, value|
      (value.is_a?(Array) ? get_values(value) : (values << value)) if key.eql? 'id'
    end
  end    
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM