简体   繁体   English

在Dart中减少/过滤地图的首选方法?

[英]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.

相关问题 在 Dart 中使用 ifAbsent 的地图更新方法 - Map Update method with ifAbsent in Dart ReactJS 映射+过滤或减少 [暂停] - ReactJS map+filter or reduce [on hold] 希望通过使用Javascript map,reduce,foreach,filter方法来实现功能 - Want to achieve functionality by using Javascripts map,reduce,foreach,filter methods 链接数组方法(过滤器、map、reduce)而不是使用双循环 - Chaining array methods (filter, map, reduce) instead of using double loop abc.filter()。map()==&gt;减少()我应该如何使用它? 的JavaScript - abc.filter().map() ==> to reduce() How should I use it? JavaScript 在js中使用Map,Reduce和filter将华氏温度转换为摄氏度 - What to use Map , Reduce and filter in js to convert fahrenheit to celcius 如何在 JavaScript 中使用 filter 来实现 map 功能,因为我们可以使用 reduce 作为 map 和 filter? - How to achieve map functionality with the use of filter in JavaScript, as we can use reduce as map and filter? 如何过滤数组然后用map的方法来output呢? - How to filter the array and then use map method to output it? 无法使用 removeWhere 过滤地图,因为尽管有非 const/final 地图(Dart/Flutter),但“无法修改不可修改的地图” - Cannot filter map using removeWhere because 'Cannot modify unmodifiable map' despite a non const/final map (Dart/Flutter) 将列表转换为 map,为什么 DART 要求您不要使用 Map.fromIterable 方法? - converting a list to a map, Why does DART ask you not to use the Map.fromIterable method?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM