Question

I want to "flatten" (not in the classical sense of .flatten) down a hash with varying levels of depth, like this:

{
  :foo => "bar",
  :hello => {
    :world => "Hello World",
    :bro => "What's up dude?",
  },
  :a => {
    :b => {
      :c => "d"
    }
  }
}

down into a hash with one single level, and all the nested keys merged into one string, so it would become this:

{
  :foo => "bar",
  :"hello.world" => "Hello World",
  :"hello.bro" => "What's up dude?",
  :"a.b.c" => "d"
}

but I can't think of a good way to do it. It's a bit like the deep_ helper functions that Rails adds to Hashes, but not quite the same. I know recursion would be the way to go here, but I've never written a recursive function in Ruby.

Was it helpful?

Solution

You could do this:

def flatten_hash(hash)
  hash.each_with_object({}) do |(k, v), h|
    if v.is_a? Hash
      flatten_hash(v).map do |h_k, h_v|
        h["#{k}.#{h_k}".to_sym] = h_v
      end
    else 
      h[k] = v
    end
   end
end

flatten_hash(:foo => "bar",
  :hello => {
    :world => "Hello World",
    :bro => "What's up dude?",
  },
  :a => {
    :b => {
      :c => "d"
    }
  })
# => {:foo=>"bar", 
# =>  :"hello.world"=>"Hello World", 
# =>  :"hello.bro"=>"What's up dude?", 
# =>  :"a.b.c"=>"d"} 

OTHER TIPS

Because I love Enumerable#reduce and hate lines apparently:

def flatten_hash(param, prefix=nil)
  param.each_pair.reduce({}) do |a, (k, v)|
    v.is_a?(Hash) ? a.merge(flatten_hash(v, "#{prefix}#{k}.")) : a.merge("#{prefix}#{k}".to_sym => v)
  end
end

irb(main):118:0> flatten_hash(hash)
=> {:foo=>"bar", :"hello.world"=>"Hello World", :"hello.bro"=>"What's up dude?", :"a.b.c"=>"d"}

The top voted answer here will not flatten the object all the way, it does not flatten arrays. I've corrected this below and have offered a comparison:

x = { x: 0, y: { x: 1 }, z: [ { y: 0, x: 2 }, 4 ] }

def top_voter_function ( hash )
  hash.each_with_object( {} ) do |( k, v ), h|
    if v.is_a? Hash
      top_voter_function( v ).map do |h_k, h_v|
        h[ "#{k}.#{h_k}".to_sym ] = h_v
      end
    else
      h[k] = v
    end
  end
end

def better_function ( a_el, a_k = nil )
  result = {}

  a_el = a_el.as_json

  a_el.map do |k, v|
    k = "#{a_k}.#{k}" if a_k.present?
    result.merge!( [Hash, Array].include?( v.class ) ? better_function( v, k ) : ( { k => v } ) )
  end if a_el.is_a?( Hash )

  a_el.uniq.each_with_index do |o, i|
    i = "#{a_k}.#{i}" if a_k.present?
    result.merge!( [Hash, Array].include?( o.class ) ? better_function( o, i ) : ( { i => o } ) )
  end if a_el.is_a?( Array )

  result
end

top_voter_function( x ) #=> {:x=>0, :"y.x"=>1, :z=>[{:y=>0, :x=>2}, 4]}
better_function( x ) #=> {"x"=>0, "y.x"=>1, "z.0.y"=>0, "z.0.x"=>2, "z.1"=>4} 

I appreciate that this question is a little old, I went looking online for a comparison of my code above and this is what I found. It works really well when used with events for an analytics service like Mixpanel.

Or if you want a monkey-patched version or Uri's answer to go your_hash.flatten_to_root:

class Hash
  def flatten_to_root
    self.each_with_object({}) do |(k, v), h|
      if v.is_a? Hash
        v.flatten_to_root.map do |h_k, h_v|
          h["#{k}.#{h_k}".to_sym] = h_v
        end
      else
        h[k] = v
      end
    end
  end
end

In my case I was working with the Parameters class so none of the above solutions worked for me. What I did to resolve the problem was to create the following function:

def flatten_params(param, extracted = {})
    param.each do |key, value|
        if value.is_a? ActionController::Parameters
            flatten_params(value, extracted)
        else
            extracted.merge!("#{key}": value)
        end
    end
    extracted
end

Then you can use it like flatten_parameters = flatten_params(params). Hope this helps.

Just in case, that you want to keep their parent

def flatten_hash(param)
  param.each_pair.reduce({}) do |a, (k, v)|
    v.is_a?(Hash) ? a.merge({ k.to_sym => '' }, flatten_hash(v)) : a.merge(k.to_sym => v)
  end
end

hash = {:foo=>"bar", :hello=>{:world=>"Hello World", :bro=>"What's up dude?"}, :a=>{:b=>{:c=>"d"}}}

flatten_hash(hash)

# {:foo=>"bar", :hello=>"", :world=>"Hello World", :bro=>"What's up dude?", :a=>"", :b=>"", :c=>"d"}

Here's a solution that worked for me:

class Hash
  # Test with:
  # {
  #   s: 1,
  #   s2: '2',
  #   n1: {},
  #   n2: { a: 1 },
  #   n3: { a: { b: 1, c: [2, 3], d: { e: 1, f: [4, 5, 'x'] } } },
  #   n4: [],
  #   n5: [1],
  #   n6: [[[[[[[['treasure', [], 1, 'n', {}, { a: 1, b: [2, 3], c: { d: 1, e: [4, 5] } }]]]]]]]],
  #   n7: [{ a: 1, b: [2, 3], c: { d: 1, e: [4, 5] } }, 'y'],
  # }.to_dotted_keys
  def to_dotted_keys(parent_key = nil, flattened_hash = {})
    each do |key, value|
      current_key = parent_key ? "#{parent_key}.#{key}" : key.to_s

      if value.is_a?(Hash) && !value.empty?
        value.to_dotted_keys(current_key, flattened_hash)
      elsif value.is_a?(Array) && !value.empty?
        value.each_with_index do |item, index|
          if item.is_a?(Hash) || item.is_a?(Array)
            { index => item }.to_dotted_keys(current_key, flattened_hash)
          else
            flattened_hash["#{current_key}.#{index}"] = item
          end
        end
      else
        flattened_hash[current_key] = value
      end
    end

    flattened_hash
  end
end

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top