जैसा कि @ डोगबर्ट ने सुझाव दिया है, आप नक्शे को दोबारा मर्ज करने के लिए एक फ़ंक्शन लिख सकते हैं।
defmodule MapUtils do
def deep_merge(left, right) do
Map.merge(left, right, &deep_resolve/3)
end
# Key exists in both maps, and both values are maps as well.
# These can be merged recursively.
defp deep_resolve(_key, left = %{}, right = %{}) do
deep_merge(left, right)
end
# Key exists in both maps, but at least one of the values is
# NOT a map. We fall back to standard merge behavior, preferring
# the value on the right.
defp deep_resolve(_key, _left, right) do
right
end
end
यहाँ कुछ परीक्षण मामलों आप इसका अंदाज़ा लगा संघर्ष हल कर रहे हैं देने के लिए कर रहे हैं:
ExUnit.start
defmodule MapUtils.Test do
use ExUnit.Case
test 'one level of maps without conflict' do
result = MapUtils.deep_merge(%{a: 1}, %{b: 2})
assert result == %{a: 1, b: 2}
end
test 'two levels of maps without conflict' do
result = MapUtils.deep_merge(%{a: %{b: 1}}, %{a: %{c: 3}})
assert result == %{a: %{b: 1, c: 3}}
end
test 'three levels of maps without conflict' do
result = MapUtils.deep_merge(%{a: %{b: %{c: 1}}}, %{a: %{b: %{d: 2}}})
assert result == %{a: %{b: %{c: 1, d: 2}}}
end
test 'non-map value in left' do
result = MapUtils.deep_merge(%{a: 1}, %{a: %{b: 2}})
assert result == %{a: %{b: 2}}
end
test 'non-map value in right' do
result = MapUtils.deep_merge(%{a: %{b: 1}}, %{a: 2})
assert result == %{a: 2}
end
test 'non-map value in both' do
result = MapUtils.deep_merge(%{a: 1}, %{a: 2})
assert result == %{a: 2}
end
end
स्रोत
2016-08-10 06:19:47
बहुत बहुत धन्यवाद !!! – asiniy
छोटी बात यह है कि यहां से अवगत होना यह है कि यह चुपचाप structs/कस्टम परिभाषित प्रकारों के साथ-साथ अंदर के नक्शे को मर्ज करेगा। इससे बचने के लिए आप '__struct__' कुंजी पर पैटर्न मिलान कर सकते हैं जो मौजूद है जब यह एक संरचना है। इन नुकसानों में पड़ने वाले लोगों से बचने के लिए मैंने एक [deep_merge] (https://github.com/PragTob/deep_merge) लाइब्रेरी भी लिखी। – PragTob