简体   繁体   中英

How is the best way to merge array of hashes based on same value of some key?

I have some array of hashes with same keys. Like this below:

entities = [
  {type: :user, name: 'Tester', phone: '0000-0000'},
  {type: :user, name: 'Another User', phone: '0000-0000'},
  {type: :company, name: 'A.C.M.E.', phone: '0000-0000'},
  {type: :user, name: 'John Appleseed', phone: '0000-0000'},
  {type: :company, name: 'Aperture Industries', phone: '0000-0000'}
]

I need to organize them based on value of some key, generating a new hash with keys based on values of some key of original hash, like type .

I do this for organize:

by_type = {}
entities.each do |entity|
  by_type[entity[:type]] ||= []
  by_type[entity[:type]] << entity
end

Resulting on what I need:

by_type = {
  user: [
    {type: :user, name: 'Tester', phone: '0000-0000'},
    {type: :user, name: 'Another User', phone: '0000-0000'},
    {type: :user, name: 'John Appleseed', phone: '0000-0000'}
  ],
  company: [
    {type: :company, name: 'A.C.M.E.', phone: '0000-0000'},
    {type: :company, name: 'Aperture Industries', phone: '0000-0000'}
  ]
}

There is another way or an elegant method to organize this?

您可以使用group_by

entities.group_by { |entity| entity[:type] }

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