Last active
December 10, 2015 00:59
-
-
Save dwickwire/4355442 to your computer and use it in GitHub Desktop.
This method can iterate over a big diverse data-set and return the hash which matches the field value.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@fields = [{ | |
:foo => [ | |
1, | |
2, | |
[ | |
3, | |
{:field => 'oranges', :options =>{ :label => "Oranges"}} | |
], | |
{:a => {:zaz => 42}}, | |
[ | |
{:field => 'apples', :options => {:label => "Apples"}}, | |
{:field => 'bananas', :options => {:label => "Bananas"}} | |
] | |
] | |
}] | |
def find_nested_hash_by_key_value(node, key, search_for) | |
if node.respond_to?(:key?) && node.key?(key) | |
if node[key] == search_for | |
node | |
end | |
elsif node.respond_to?(:each) | |
r = nil | |
node.find{ |*a| r=find_nested_hash_by_key_value(a.last,key,search_for) } | |
r | |
end | |
end | |
search_for = "apples" | |
puts find_nested_hash_by_key_value(@fields, :field, search_for) | |
## => {:field => 'apples', :options => {:label => "Apples"}} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment