ruby-on-rails – 从ruby中的嵌套哈希数组中搜索键值
发布时间:2020-12-17 03:49:29 所属栏目:百科 来源:网络整理
导读:我有嵌套哈希数组, @a = [{"id"="5","head_id"=nil,"children"= [{"id"="19","head_id"="5","children"= [{"id"="21","head_id"="19","children"=[]}]},{"id"="20","children"= [{"id"="22","head_id"="20","children"=[]},{"id"="23"}] }] }] 我需要所有具
|
我有嵌套哈希数组,
@a = [{"id"=>"5","head_id"=>nil,"children"=>
[{"id"=>"19","head_id"=>"5","children"=>
[{"id"=>"21","head_id"=>"19","children"=>[]}]},{"id"=>"20","children"=>
[{"id"=>"22","head_id"=>"20","children"=>[]},{"id"=>"23"}]
}]
}]
我需要所有具有键名称’id’的值的数组.像@b = [5,19,21,20,22,23] 谢谢. 解决方法
您可以为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" (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
