flutter
flutter

Reputation: 6786

Extracting map from a map in dart

How would I convert this map

{
  "country": "uk",
  "postcode": "500",
  "suburbs": [
    {
      "code": "liverpool",
      "name": "liverpool"
    },
    {
      "code": "merseyside",
      "name": "merseyside"
    }
  ]
}

to

{
  "country": "uk",
  "postcode": "500",
  "suburb":"liverpool"

}

Upvotes: 0

Views: 31

Answers (1)

julemand101
julemand101

Reputation: 31299

I guess you have tried it yourself first but ended up in type problems since your map contains elements of different types.

You can declare your Map in such way that the compiler knows the types are dynamic (which disables type safety):

void main() async {
  final mapFrom = <String, dynamic>{
    "country": "uk",
    "postcode": "500",
    "suburbs": [
      {"code": "liverpool", "name": "liverpool"},
      {"code": "merseyside", "name": "merseyside"}
    ]
  };

  final mapTo = {
    "country": mapFrom["country"],
    "postcode": mapFrom["country"],
    "suburbs": mapFrom["suburbs"][0]["code"]
  };

  print(mapTo); // {country: uk, postcode: uk, suburbs: liverpool}
}

Or the following if you want to modify a map:

  final mapTo = Map.of(mapFrom);
  mapTo["suburbs"] = mapTo["suburbs"][0]["code"];

Upvotes: 1

Related Questions