简体   繁体   中英

Dart - How to convert nested Map<dynamic, dynamic> to Map<String, dynamic>

I know how to convert Map<dynamic, dynamic> to Map<String, dynamic> using Map.from() method. But what if I have unspecified number of nested Maps inside? How to convert all potential children as well from Map<dynamic, dynamic> to Map<String, dynamic> ?

Same answer as fravolt's but I was unable do put code in comments:

Map.forEach do not treats value by reference. You may change to:

// recursively convert the map
Map<String, dynamic> convertMap(Map<dynamic, dynamic> map) {
    for (var key in map.keys) {
      if (map[key] is Map) {
        map[key] = convertMap(map[key]);
      }
    }  // use .from to ensure the keys are Strings
  return Map<String, dynamic>.from(map);
  // more explicit alternative way:
  // return Map.fromEntries(map.entries.map((entry) => MapEntry(entry.key.toString(), entry.value)));
}

You could use a recursive approach to this problem, where all map values of type Map are recursively converted as well.

// recursively convert the map
Map<String, dynamic> convertMap(Map<dynamic, dynamic> map) {
  map.forEach((key, value) {
    if (value is Map) {
      // it's a map, process it
      value = convertMap(value);
    }
  });
  // use .from to ensure the keys are Strings
  return Map<String, dynamic>.from(map);
  // more explicit alternative way:
  // return Map.fromEntries(map.entries.map((entry) => MapEntry(entry.key.toString(), entry.value)));
}

// example nested map with dynamic values
Map<dynamic, dynamic> nestedMap = {
  'first': 'value',
  'second': {
    'foo': 'bar',
    'yes': 'ok',
    'map': {'some': 'value'},
  }
};

// convert the example map
Map<String, dynamic> result = convertMap(nestedMap);
print(result);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM