Delete selected keys from Dart Map

你。 提交于 2020-02-29 11:41:04

问题


What is the Dart idiomatic way to remove selected keys from a Map? Below I'm using a temporary emptyList to hold String keys. Is there a cleaner way?

List<String> emptyList = new List<String>();
_objTable.keys.forEach((String name) { 
  if (_objTable[name].indices.isEmpty) {
    emptyList.add(name);
    print("OBJ: deleting empty object=$name loaded from url=$url");
  } 
});
emptyList.forEach((String name) => _objTable.remove(name));

回答1:


You can do something like this :

_objTable.keys
  .where((k) => _objTable[k].indices.isEmpty) // filter keys
  .toList() // create a copy to avoid concurrent modifications
  .forEach(_objTable.remove); // remove selected keys



回答2:


Simply do:

_objTable.removeWhere((key, value) => key == "propertyName");

It works with nested Maps too.



来源:https://stackoverflow.com/questions/17038512/delete-selected-keys-from-dart-map

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!