Skip to content

Instantly share code, notes, and snippets.

@dwickwire
Last active December 10, 2015 00:59
Show Gist options
  • Save dwickwire/4355442 to your computer and use it in GitHub Desktop.
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.
@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