I am new to flutter/dart, i have to replace a map with another map only when there is key match between them else leave the first map as it is. This should work like array_replace_recursive() function in PHP.
Here is the code sample:
map1 = {
"t":{
"l":{
"-2":{
"n":"rocky",
"e":"[email protected]",
"r":"23567"
}
},
"o":{
"xyz":{
"p":"hi",
"x":"cdcbcbk"
}
}
},
"lang":{
"eng":"english",
"spn":"spanish"
}
"sc":{
"math"{
"lb":"30",
"pr":"60"
}
}
}
i have to overide it with
map2 = {
"t":{
"l":{
"-2":{
"n":"rohit",
}
},
},
}
expected output should be
finalMap = {
"t":{
"l":{
"-2":{
"n":"rohit",
"e":"[email protected]",
"r":"23567"
}
},
"o":{
"xyz":{
"p":"hi",
"x":"cdcbcbk"
}
}
},
"lang":{
"eng":"english",
"spn":"spanish"
}
"sc":{
"math"{
"lb":"30",
"pr":"60"
}
}
}
Thanks
CodePudding user response:
Check this once, made changes based on your specification
replaceIfSame(Map a,Map b){
b.keys.forEach((k){
if(a.containsKey(k)){
if(a[k] is Map && b[k] is Map){
replaceIfSame(a[k],b[k]);
}
else{
a[k] = b[k];
}
}
});
}
Here replaceIfSame is a function that I call recursively passing the maps as input.
Do specify if it's not the case.
Cheers!!
CodePudding user response:
I tried below method it also gives the same result but i'm not sure whether it is efficient or not
Map<dynamic, dynamic> mergemap(Map map1, Map map2) {
map2.forEach((k, v) {
if (map1.containsKey(k)) {
if (v.runtimeType != String) {
mergemap(map1[k], v);
} else {
map1[k] = v;
}
}
});
return map1;
}