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);
}
Run Code Online (Sandbox Code Playgroud)
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.
小智 28
仅供参考
现在您可以使用 Map 类的每个实例中的特殊方法。
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
Run Code Online (Sandbox Code Playgroud)
从 Dart SDK 2.2.1 开始,您可以使用集合作为语法。这适用于地图和列表(文档)。
例子:
Map m = {'1': 1, '2':2 };
final newMap = {
for (var k in m.keys)
k: m[k] * 5,
};
Run Code Online (Sandbox Code Playgroud)
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 );
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2914 次 |
| 最近记录: |