Find the parent of a child in a nested hash

I have a nested hash as shown below and I want to find the parent for a specific child using ruby.

For example, I want to find the parent for "field3": 123 (12345 is the parent if my entries are confusing)

[
{
  "12345": [
    {
      "entry_id": 543,
      "field1": "value",
      "field2": "other value",
      "field3": 123
    },
    {
      "entry_id": 544,
      "field1": "something",
      "field2": "something else",
      "field3": 456
    }
  ],
  "23456": [
    {
      "entry_id": 545,
      "field1": "new value",
      "field2": "other new value",
      "field3": 789
    },
    {
      "entry_id": 546,
      "field1": "something!",
      "field2": "something else!",
      "field3": 012
    }
  ]
}
]

      

I can iterate over the hash and print the parent I want, but is there a more efficient way to do this?

I've looked at some of the other answers and I found this code here :

def dfs(obj, &blk)
  return enum_for(:dfs, obj) unless blk      
  yield obj if obj.is_a? Hash
  if obj.is_a?(Hash) || obj.is_a?(Array)
    obj.each do |*a|
      dfs(a.last, &blk)
    end
  end
end


def find_node_with_value(obj, key, value)
  dfs(obj).select do |node|
    node[key].respond_to?(:include?) && node[key].include?(value)
  end
end

      

Of course the above code helps me find the child nodes. How do I find a parent for a specific child I'm looking for?

+3


source to share





All Articles