Using the following List of Maps, I would like to create a kind of statistical summary in order to be able to create a plot from it.
List<dynamic> data = [
{
"SoftwareVersion": "10.09.21",
"Controller": "P1",
},
{
"SoftwareVersion": "11.11.03",
"Controller": "P1",
},
{
"SoftwareVersion": "11.11.03",
"Controller": "P2",
},
{
"SoftwareVersion": "28.09.04",
"Controller": "P2",
},
{
"SoftwareVersion": "28.09.04",
"Controller": "P2",
},
{
"SoftwareVersion": "28.09.04",
"Controller": "P3",
}];
The expected outcome from the list above should look like the list below. So that for each available controller I get a count for the actual used SoftwareVersion.
List newData = [
{
"P1": {
"10.09.21": 1,
"11.11.03": 1,
},
"P2": {
"11.11.03": 1,
"28.09.04": 2
},
"P3": {
"28.09.04": 1
}
}];
CodePudding user response:
Just iterate over the list adding to the newData
map. Be careful to add an empty value if this controller or version hasn't been seen before - use the handy putIfAbsent
for that. (Note that I removed the unnecessary outer list from newData
);
void main() {
data.forEach(addToNewData);
print(newData);
}
void addToNewData(Map<String, String> e) {
final version = e['SoftwareVersion']!;
final controller = e['Controller']!;
final controllerMap = newData.putIfAbsent(controller, () => <String, int>{});
controllerMap[version] = controllerMap.putIfAbsent(version, () => 0) 1;
}
final newData = <String, Map<String, int>>{};