filterByKeys method
Filters the map by specified keys and returns a new map containing only the selected key-value pairs.
The keys parameter is a list of strings representing the keys to retain in the resulting map. The method iterates over the provided keys and includes only those entries in the new map whose keys are present in the keys list.
Returns a new map with entries that match the specified keys. If a key from keys does not exist in the original map, it is ignored.
Example:
Map<String, Map> strategies = {
"smart": {
"title": "SMART",
"tracker": "target",
"step": {
"singular": "Step",
"plural": "Steps",
},
"subtitle": "An effective way that provides the clarity and focus you need to achieve your goals."
},
"hard": {
"title": "HARD",
"tracker": "challenge",
"step": {
"singular": "Challenge",
"plural": "Challenges",
},
"subtitle": "Goals like paying off debt or waking up early every day are common challenges that will do well with this framework."
},
// Add other strategies...
};
var filteredStrategies = strategies.filterByKeys(['smart']);
print(filteredStrategies);
// Output: Map containing only the entries for 'smart' and 'hard' keys.
Implementation
Map<String, Map> filterByKeys(List<String> keys) {
return Map.fromIterables(
keys.where((key) => this.containsKey(key)),
keys.where((key) => this.containsKey(key)).map((key) => this[key]!),
);
}