Created
July 2, 2020 09:42
-
-
Save blocknotes/3385f791e9b98fdb74a48b8970300b37 to your computer and use it in GitHub Desktop.
Flatten recursively an hash / array of nested hashes / arrays
This file contains 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_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