[英]Search for key-value from array of nested hash in ruby
我有嵌套哈希數組,
@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"}]
}]
}]
我需要所有具有鍵名稱'id'的值的數組。 比如@b = [5,19,21,20,22,23]我已經試過這個'@a.find {| h | H [ 'ID']}`。 有誰知道如何得到這個?
謝謝。
您可以為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
使用這種方法就像
@a.find_recursive_with "id", :nested => "children"
它可以這樣做,使用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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.