您可以使用Enum.group_by/2 按id 分组,然后对于每个组,将role 传递给Enum.flat_map/2 和Enum.uniq/1:
list = [%{"id": 1, "role": ["A", "B"]}, %{"id": 2, "role": ["B", "C"]}, %{"id": 1, "role": ["C", "A"]} ]
list
|> Enum.group_by(&(&1.id))
|> Enum.map(fn {key, value} ->
%{id: key, role: value |> Enum.flat_map(&(&1.role)) |> Enum.uniq}
end)
|> IO.inspect
输出:
[%{id: 1, role: ["A", "B", "C"]}, %{id: 2, role: ["B", "C"]}]
根据下面评论中的要求,以下是如何保留所有键/值对并仅修改组中第一项的role:
list = [%{"id": 1, "role": ["A", "B"], "somekey": "value of the key 1"},
%{"id": 2, "role": ["B", "C"], "somekey": "value of the key 2"},
%{"id": 1, "role": ["C", "A"], "somekey": "value of the key 3"}]
list
|> Enum.group_by(&(&1.id))
|> Enum.map(fn {_, [value | _] = values} ->
%{value | role: values |> Enum.flat_map(&(&1.role)) |> Enum.uniq}
end)
|> IO.inspect
输出:
[%{id: 1, role: ["A", "B", "C"], somekey: "value of the key 1"},
%{id: 2, role: ["B", "C"], somekey: "value of the key 2"}]