Created
September 28, 2021 15:37
-
-
Save ftuyama/5bf916d052cb35e38236f357880b8628 to your computer and use it in GitHub Desktop.
Recursive flattening json object
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
def flatten_hash(param, prefix=nil) | |
param.each_pair.reduce({}) do |a, (k, v)| | |
if v.is_a?(Array) | |
v = v.map.with_index { |x, i| [i, x] }.to_h | |
end | |
if v.is_a?(Hash) | |
a.merge(flatten_hash(v, "#{prefix}#{k}.")) | |
else | |
a.merge("#{prefix}#{k}".to_sym => v) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment