在flutter中收集从api到列表的计数和存储数据



我有一个来自api的json列表,需要收集列表中的状态计数并存储在一个新列表中。来自api的Json列表,如:

"data": [
{
"_id": "1",
"status": [
{
"status": "A",
"count": 6
},
{
"status": "B",
"count": 5
},


],

},
{
"_id": "2",
"status": [
{
"status" : "S",
"count" : 17
},
{
"status": "A",
"count": 2
},


],
}
]

我需要收集状态列表的计数,如:"计数":[{"状态":"A";,"count":8.},{"状态":"B";,"count":5.},{"状态":"S";,"count":17},

]

我制作了一个稍短的版本,更新了列表元素,而不是删除和再次添加。请参阅以下行之间的更改。

然后,我还在结尾添加了一个奖金!

[
{status: A, count: 8}
{status: B, count: 5},
{status: S, count: 17},
]

新的输出是:

[
{status: B, count: 5},
{status: S, count: 17},
{status: A, count: 8}
]

(旧的输出是:

Map finalMap = {
'counts': summedUpCounts
};

)

请随意将其放入地图中,如:

{
'A': 8,
'B': 5,
'S': 17
}

如果你喜欢的话!


编辑:

作为一个额外的奖励,我只是在想:对你来说,把地图上的信息改成这样不是更容易吗:

print(listOfStatusMap);
Map statusAndCount = {};
for (Map statusMap in listOfStatusMap) {
bool statusAlreadyExists = false;
late int sum;
for (String status in statusAndCount.keys) {
// If the same status already exists in the statusAndCount Map:
if (statusMap['status'] == status) {
print('Status $status already exists in statusAndCount Map!');
statusAlreadyExists = true;
sum = statusAndCount[status] + statusMap['count']; // Old value added to new value of count
break;  // We can break this for-loop, coz there's not supposed to be TWO keys
// with the same status in the statusAndCount, ever!
}
}
// Very important that this code be placed outside the inner for-loop!
if (statusAlreadyExists) {
statusAndCount[statusMap['status']] = sum;
} else {
statusAndCount.addAll({
statusMap['status']: statusMap['count']
});
}
}
print(statusAndCount);

然后你就会知道,键是状态,值是计数,而不需要保留单词";"状态";以及";计数";在对象中!

如果你想要这个,你可以用交换上面CCD_2的代码

{
A: 8,
B: 5,
S: 17
}

现在,输出是:

PD_9从这里开始,似乎所有的代码都会变短,如果你这样做的话。。。!

相关内容

  • 没有找到相关文章

最新更新