mergeNested method

Map<String, dynamic> mergeNested(
  1. Map<String, dynamic> other
)

Merges the current map with another map recursively. If there are duplicate keys and both values are maps, they are merged recursively. Otherwise, the values from the other map will overwrite those in the current map. If other is null, the current map is returned unchanged.

Example usage:

void main() {
  final Map<String, dynamic> map1 = {
    'a': 1,
    'b': {'c': 2, 'd': 3},
    'e': 4,
  };
  final Map<String, dynamic> map2 = {
    'b': {'c': 3, 'd': 4},
    'f': 5,
  };
  final Map<String, dynamic> mergedMap = map1.mergeNested(map2);
  print(mergedMap); // Output: {a: 1, b: {c: 3, d: 4}, e: 4, f: 5}
}

Implementation

Map<String, dynamic> mergeNested(Map<String, dynamic> other) {
  final result = Map<String, dynamic>.from(this);
  other.forEach((key, otherValue) {
    if (result.containsKey(key)) {
      final thisValue = result[key];
      if (thisValue is Map<String, dynamic> && otherValue is Map<String, dynamic>) {
        result[key] = thisValue.mergeNested(otherValue);
      } else if (otherValue != null) {
        result[key] = otherValue;
      }
    } else {
      result[key] = otherValue;
    }
  });
  return result;
}