Find key/value pairs deep inside a hash containing an arbitrary number of nested hashes and arrays

前端 未结 9 1064
天涯浪人
天涯浪人 2020-12-02 20:12

A web service is returning a hash that contains an unknown number of nested hashes, some of which contain an array, which in turn contains an unknown number of nested hashes

9条回答
  •  悲&欢浪女
    2020-12-02 20:40

    Because Rails 5 ActionController::Parameters no longer inherits from Hash, I've had to modify the method and make it specific to parameters.

    module ActionController
      class Parameters
        def deep_find(key, object=self, found=nil)
          if object.respond_to?(:key?) && object.key?(key)
            return object[key]
          elsif object.respond_to?(:each)
            object = object.to_unsafe_h if object.is_a?(ActionController::Parameters)
            object.find { |*a| found = deep_find(key, a.last) }
            return found
          end
        end
      end
    end
    

    If the key is found, it returns the value of that key, but it doesn't return an ActionController::Parameter object so Strong Parameters are not preserved.

提交回复
热议问题