0

我有以下哈希。如何获得唯一和合并的哈希。

[
 {
  "email"=>"user_name@aaa.com",
  "expression"=>"aaa",
  "name"=>"bbb",
  "roles"=>[:admin]
  },

  {
   "email"=>"user_name@aaa.com",
   "expression"=>"aaa",
   "name"=>"bbb",
   "roles"=>[:manager]
  }
]

我希望下面的结果哈希通过电子邮件唯一并按角色合并。

[
  {
    "email"=>"user_name@aaa.com",
    "expression"=>"aaa",
    "name"=>"bbb",
    "roles"=>[:admin, :manager]
  }
]

帮我。

4

3 回答 3

2

试试这个

a.group_by { |item| item["email"] }.each_with_object([]) do |(_, items), arr| 
  arr.concat([items.first.merge("roles" => items.flat_map { |item| item["roles"] }.uniq)])
end
于 2018-05-31T12:12:29.127 回答
1
input.
  group_by { |e| e['email'] }.
  map do |_, v|
    v.reduce do |acc, h|
      acc.merge(h) { |_, v1, v2| v1 == v2 ? v1 : [*v1, *v2] }
    end
  end
#⇒ [{"email"=>"user_name@aaa.com",
#    "expression"=>"aaa",
#    "name"=>"bbb",
#    "roles"=>[:admin, :manager]}]
于 2018-05-31T12:57:42.580 回答
0
arr = [{ "email"=>"user_name@aaa.com", "expression"=>"aaa", "name"=>"bbb",
         "roles"=>[:admin] },
       { "email"=>"user_name@aaa.com", "expression"=>"aaa", "name"=>"bbb",
         "roles"=>[:manager] }]

arr.first.merge("roles"=>arr.map { |h| h["roles"].first })
  #=> {"email"=>"user_name@aaa.com", "expression"=>"aaa", "name"=>"bbb",
  #    "roles"=>[:admin, :manager]}

步骤如下。

h = arr.first
  #=> {"email"=>"user_name@aaa.com", "expression"=>"aaa", "name"=>"bbb",
  #    "roles"=>[:admin]}
a = arr.map { |h| h["roles"].first }
  #=> [:admin, :manager]
g = { "roles"=>a }
  #=> {"roles"=>[:admin, :manager]}
h.merge(g)
  #=> {"email"=>"user_name@aaa.com", "expression"=>"aaa", "name"=>"bbb",
  #    "roles"=>[:admin, :manager]}

请注意,Ruby 允许将哈希作为方法参数写入其键值对的序列。例如:

receiver.doit({ a: 1, b: 2})

可以写

receiver.doit(a: 1, b: 2)
于 2018-05-31T20:56:50.970 回答