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));
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.
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.
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 .
Simply do:
_objTable.removeWhere((key, value) => key == "propertyName");
It works with nested Maps too.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With