14

I like the .map((item){/*mapper*/}) that is on the Iterable classes, but the Map class doesn't appear to implement an analogous method. When I want to do the following, I have to create an blank instance and then forEach over the existing Map I want to map to the new instance type:

void noSuchMethod(Invocation inv){
  if(inv.isMethod){
    var namedArguments = new Map<String, dynamic>();
    inv.namedArguments.forEach((k, v){
      namedArguments[MirrorSystem.getName(k)] = v;
    });
    return;
  }
  super.noSuchMethod(inv);
}

Is there a nicer way of mapping Maps? It seems a litle odd that there is a forEach((v){}) for Iterables and a forEach((k, v){}) for Maps but not a map((k, v){}) for Maps.

3 Answers 3

31

Just for info

Now you can use a special method that is in every instance of the Map class.

final dict = { "id": 1, "name": "Alex", "isAdmin": true };
// A simple map, that contains a user's info

dict.map((key, value) => MapEntry(key, value.toString()));
// Here we can transform the key and the value of this map

print(dict);
// { "id": "1", "name": "Alex", "isAdmin": "true" }
// All fields are strings now
2
  • 1
    Perfect! This is much more analogous to List.map() than the other proposed solutions, and much more succinct.
    – rickb
    Commented Jun 12, 2021 at 16:22
  • For a more complete example, I created the following gist: gist.github.com/rickbsgu/6af051158fd4c32fff188b3256c7e705. You can paste it into dartpad to see it work.
    – rickb
    Commented Jun 12, 2021 at 20:31
10

Since Dart SDK 2.2.1, you can use the collection for syntax. This works for maps as well as lists (docs).

Example:

Map m = {'1': 1, '2':2 };

final newMap = {
  for (var k in m.keys)
    k: m[k] * 5,
};
9

This should do what you want:

Map m = {'1': 1, '2':2 };
var newMap = new Map.fromIterable(m.keys, key: (k) => k , value: (v) => m[v] * 5 );
3
  • 2
    thanks that's great, I'll use this for now, it would still be nice to have a map((k, v){}) method for Maps though. Commented Mar 16, 2014 at 11:07
  • 1
    You should create a feature request on dartbug.com then (if there isn't already). If you do post the link here so people know where to find it and can star. Commented Mar 16, 2014 at 11:09
  • @DanielRobinson It's late but there is now. For example newmap = oldmap.map((key, value) => MapEntry(key, value)); is the same as newmap = oldmap. I am not sure if the object is the same. Commented Aug 18, 2021 at 13:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.