您可以根据需要使用此功能:
t = [
%{
localtions: [],
doctors: [%{name: "Junaid", hospital: "west"}, %{name: "Farooq", hospital: "test"}]
},
%{
localtions: [%{name: "Dom", address: "test"}, %{name: "Dom", address: "west"}],
doctors: []
},
%{localtions: [], doctors: []},
%{
localtions: [%{name: "Dominic", address: "test"}, %{name: "DomDom", address: "west"}],
doctors: []
}
]
函数定义为:
def name_is_unique(l) do
Enum.reduce(l, %{}, fn x, mp ->
Map.merge(mp, x, fn _k, v1, v2 ->
Enum.reduce(v1 ++ v2, %{}, fn x, acc -> Map.put(acc, x.name, x) end)
|> Map.values()
end)
end)
end
def duplication_check(l) do # with duplication check
Enum.reduce(l, %{}, fn x, mp ->
Map.merge(mp, x, fn _k1, mpV1, mpV2 ->
(mpV1 ++ mpV2) # [%{name: "Dom"}, %{name: "Dom"}]
|> Enum.reduce(MapSet.new(), fn inerListMap, inerMapSet ->
MapSet.put(inerMapSet, inerListMap) # %{name: "Dom"}
end)
|> MapSet.to_list()
end)
end)
end
def with_duplication(l) do
Enum.reduce(l, %{}, fn x, mp ->
Map.merge(mp, x, fn _k1, mpV1, mpV2 ->
mpV1 ++ mpV2
end)
end)
end
如果您的唯一性是 name 键,则使用 name_is_unique 或者如果您希望地图项的完全唯一性使用 duplication_check 并且不关心重复使用 with_duplication
name_is_unique(t)
%{
doctors: [
%{hospital: "test", name: "Farooq"},
%{hospital: "west", name: "Junaid"}
],
localtions: [
%{address: "west", name: "Dom"},
%{address: "west", name: "DomDom"},
%{address: "test", name: "Dominic"}
]
}
duplication_check(t)
%{
doctors: [
%{hospital: "test", name: "Farooq"},
%{hospital: "west", name: "Junaid"}
],
localtions: [
%{address: "test", name: "Dom"},
%{address: "test", name: "Dominic"},
%{address: "west", name: "Dom"},
%{address: "west", name: "DomDom"}
]
}
with_duplication(t)
%{
doctors: [
%{hospital: "west", name: "Junaid"},
%{hospital: "test", name: "Farooq"}
],
localtions: [
%{address: "test", name: "Dom"},
%{address: "west", name: "Dom"},
%{address: "test", name: "Dominic"},
%{address: "west", name: "DomDom"}
]
}