Home > front end >  How to combine array of hashes into one array?
How to combine array of hashes into one array?

Time:10-05

I'm trying to combine an array of hashes like this:

[{:locale=>:"en-US", :key=>:key1}, {:locale=>:"en-US", :key=>:key2}, {:locale=>:da, :key=>:key1}]

Into one array like this:

['locale', 'en-US', 'key', 'key1', 'locale', 'en-US', 'key', 'key2', 'locale', 'da', 'key', 'key1']

How can I do this?

CodePudding user response:

Input

a=[{:locale=>:"en-US", :key=>:key1}, {:locale=>:"en-US", :key=>:key2}, {:locale=>:da, :key=>:key1}]

Code

result=a.map do |h|
  h.map do|k,v|
    [k,v]
  end
end.flatten
p result

Or

p a.flat_map(&:to_a).flatten

Output

[:locale, :"en-US", :key, :key1, :locale, :"en-US", :key, :key2, :locale, :da, :key, :key1]

CodePudding user response:

Or, even quicker and easier:

array = [{:locale=>:"en-US", :key=>:key1}, {:locale=>:"en-US", :key=>:key2}, {:locale=>:da, :key=>:key1}]
array.map { |hash| [hash.keys, hash.values] }.flatten
  • Related