Skip to content

Instantly share code, notes, and snippets.

@blocknotes
Created July 2, 2020 09:42
Show Gist options
  • Save blocknotes/3385f791e9b98fdb74a48b8970300b37 to your computer and use it in GitHub Desktop.
Save blocknotes/3385f791e9b98fdb74a48b8970300b37 to your computer and use it in GitHub Desktop.
Flatten recursively an hash / array of nested hashes / arrays
def flatten_obj(obj, keys = [], values = {})
if obj.is_a?(Array)
obj.each_with_index do |value, index|
temp_keys = keys + [index]
if value.is_a?(Array) || value.is_a?(Hash)
flatten_obj(value, temp_keys, values)
else
values[temp_keys.join('.')] = value
end
end
elsif obj.is_a?(Hash)
obj.each do |key, value|
temp_keys = keys + [key]
if value.is_a?(Array) || value.is_a?(Hash)
flatten_obj(value, temp_keys, values)
else
values[temp_keys.join('.')] = value
end
end
end
values
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment