我有以下列表:
l = [
%{id: 1, name: "aash", possess: "car"},
%{id: 1, name: "aash", possess: "bike"},
%{id: 2, name: "rahul", possess: "scooter"}
]
我想将其转换为以下格式:
ans = [
%{id: 1, name: "aash", possess: ["car", "bike"]},
%{id: 2, name: "rahul", possess: ["scooter"]}
]
关于如何在灵药中做到这一点的任何想法?由于所有变量都是不可变的,我不知道如何实现上述转换。
答案 0 :(得分:7)
我将Enum.group_by/3
与mapper函数(第三个参数)一起使用,仅返回possess
字段。
[
%{id: 1, name: "aash", possess: "car"},
%{id: 1, name: "aash", possess: "bike"},
%{id: 2, name: "rahul", possess: "scooter"}
]
|> Enum.group_by(&{&1.id, &1.name}, & &1.possess)
|> Enum.map(fn {{id, name}, possess} ->
%{id: id, name: name, possess: possess}
end)
|> IO.inspect
输出:
[%{id: 1, name: "aash", possess: ["car", "bike"]},
%{id: 2, name: "rahul", possess: ["scooter"]}]
答案 1 :(得分:2)
l
|> Enum.group_by(fn %{id: id, name: name} -> [id, name] end)
|> Enum.map(fn {[k, v], m} ->
%{id: k, name: v, possess: Enum.map(m, & &1.possess)}
end)
#⇒ [
# %{id: 1, name: "aash", possess: ["car", "bike"]},
# %{id: 2, name: "rahul", possess: ["scooter"]}
# ]
在通用字段的情况下,解决方案会稍微复杂一些,在最后一步涉及Enum.reduce/3
而不是Enum.map/2
。