expandFlattenedJson method

Map<String, dynamic> expandFlattenedJson(
  1. Map<String, dynamic> input, {
  2. String separator = '.',
})

Adds a shortened alias key for every path suffix of every key in a flattened map, so a leaf can also be looked up by the tail of its path: {'a.b.c': 1} becomes {'a.b.c': 1, 'b.c': 1, 'c': 1}.

The original keys are kept. An alias never replaces a key that is already present: a key in input always wins, and when two paths share a tail ({'x.c': 1, 'y.c': 2}), the alias c points at whichever path comes first in input's iteration order.

This does not rebuild nested maps ({'a.b': 1} is not turned into {'a': {'b': 1}}); for that, see unflattenJson.

Implementation

Map<String, dynamic> expandFlattenedJson(
  Map<String, dynamic> input, {
  String separator = '.',
}) {
  final res = {...input};
  var modified = true;
  while (modified) {
    final currentRes = {...res};
    modified = false;
    for (final entry in currentRes.entries) {
      final key = entry.key;
      final value = entry.value;
      final parts = key.split(separator);
      if (parts.length > 1) {
        final modifiedKey = parts.sublist(1).join(separator);
        if (!res.containsKey(modifiedKey)) {
          res[modifiedKey] = value;
          modified = true;
        }
      }
    }
  }

  return res;
}