[英]Preferred method to reduce/filter a Map in Dart?
Trying to find the cleanest way to reduce a Map in Dart. 试图找到最简洁的方法来缩小Dart中的Map。 Looking for something akin to JavaScript's
Array.prototype.filter()
寻找类似于JavaScript的
Array.prototype.filter()
Any suggestions? 有什么建议么? The following method leaves a lot to be desired:
以下方法有很多不足之处:
Map ingredients = {
'flour': '250g',
'butter': '50g',
'egg': 1,
'water': '0.2l'
};
final flour = new Map.fromIterable(
ingredients.keys.where((k) => ingredients[k] == '250g'),
value: (k) => ingredients[k]
);
print(flour); // {flour: 250g}
There is no built in support for Pairs in the core library. 核心库中没有对对的内置支持。 However if you find yourself doing this type of thing often, you could write a utility library.
但是,如果您发现自己经常做这种事情,则可以编写一个实用程序库。 For example:
例如:
library pairs;
class Pair<K,V> {
Pair(this.k, this.v)
final K k;
final V v;
String toString() => '($k, $v)';
}
Iterable<Pair> asPairs(Map map) => map.keys.map((k) => new Pair(k, map[k]));
Map fromPairs(Iterable<Pair> pairs) => new Map.fromIterables(
pairs.map((p) => p.k),
pairs.map((p) => p.v));
Then you can use it like this: 然后,您可以像这样使用它:
import 'src/pairs.dart';
Map flour = fromPairs(asPairs(ingredients).where((p) => p.v == '250g'));
print(flour); // {flour: 250g}
Perhaps this is something that could be contributed to the quiver package , a set of non-core utilities. 也许这可以归因于quiver软件包 (一组非核心实用程序)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.