groupByField method
Groups the map's inner items based on a specified field.
This extension method applies to a map structure where each key contains another map. It groups these inner maps by the specified field.
Parameters: fieldName (String): The field name by which to group the maps.
Returns: Map<String, List<Map<String, dynamic>>>: A map where each key is a unique value of the specified field, and the value is a list of all maps that contain that field value.
Example:
Map<String, dynamic> data = {
"24":{"priority":"hight","title":"s1"},
"25":{"priority":"low","title":"s2"},
};
var groupedData = data.groupByField('priority');
print(groupedData);
Implementation
Map<String, List<Map<String, dynamic>>> groupByField(String fieldName) {
Map<String, List<Map<String, dynamic>>> groupedMap = {};
this.forEach((key, value) {
Map innerMap = value;
innerMap.forEach((innerKey, innerValue) {
if (innerValue is Map<String, dynamic> && innerValue.containsKey(fieldName)) {
String fieldValue = innerValue[fieldName].toString();
groupedMap[fieldValue] ??= [];
groupedMap[fieldValue]!.add(Map<String, dynamic>.from(innerValue));
}
});
});
return groupedMap;
}