Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete selected keys from Dart Map

Tags:

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)); 
like image 909
Everton Avatar asked Jun 11 '13 07:06

Everton


People also ask

How do you remove a key from a Dart map?

remove() function in Dart removes a specific element (key-value pair) from the map. If the key is found in the map, the key-value pair is removed and the key is returned. If the key is not found in the map, null is returned.

How do you delete multiple elements from a list in Dart?

Using .remove(Object value) If there are multiple elements with value 'one', only the first one will be removed. If you need to remove multiple matching elements, use . removeWhere() instead. For List of objects, matching is done by the object instance.

How do you know if a Dart map contains a key?

containsKey() function in Dart is used to check if a map contains the specific key sent as a parameter. map. containsKey() returns true if the map contains that key, otherwise it returns false .


2 Answers

Simply do:

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

It works with nested Maps too.

like image 147
Andreskiu Avatar answered Jan 01 '23 22:01

Andreskiu


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 
like image 27
Alexandre Ardhuin Avatar answered Jan 01 '23 20:01

Alexandre Ardhuin