简体   繁体   中英

Trying to sort a hash within an array within a hash

This is what my awkward DB looks like atm. I want to try and sort the nested hashes based on age. I've looked around on SO and all i can find is how to sort hashes inside of hashes, but not when the nested hashes are inside of an array. Im sure there's some easy way to either change the structure or sort it the way it is.

{ :room1 => [{
  :fred => { :name => "Fred", :age => 23 },
  :joan => { :name => "Joan", :age => 18 },
  :pete => { :name => "Pete", :age => 54 }
}],
:room2 => [{
  :jan => { :name => "jan", :age => 2 },
  :eric => { :name => "eric", :age => 3 },
  :stan => { :name => "stan", :age => 1 }
}]}

Thanks in advance! Btw, this is my first question on here. Be gentle ^^.

Try this one

h.each do |k, v| 
  h[k] = v.first.sort_by { |_, person| person[:age] }.to_h
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM