Search for a key value from an array of nested hash in ruby
I have an array of nested hash, which 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 an array of all values ββhaving the key name 'id'. like @b = [5,19,21,20,22,23] I already tried this'@a.find {| h | h ['ID']} `. Does anyone know how to get this?
Thank.
You can create a new method for class objects Array.
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 look like
@a.find_recursive_with "id", :nested => "children"
This can be done 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