gpt4 book ai didi

flutter - 如何从DART/Flutter中的数组中获取按天分组的每天的值总和?

转载 作者:行者123 更新时间:2023-12-03 03:57:21 24 4
gpt4 key购买 nike

您好,如何获取按createdTime日分组的对象列表下面的isWatch属性的总和?

[
{
"videoId": 1,
"videoName": "Test Video 1",
"duration": 300,
"createdTime": "1969-07-20 20:18:04Z",
"isWatch": 1,
},
{
"videoId": 2,
"videoName": "Test Video 2",
"duration": 500,
"createdTime": "1969-07-20 20:18:04Z",
"isWatch": 10,
}
]

最佳答案

(针对阿米特·库马尔的评论进行了编辑)

我认为最简单的方法是:

    import "package:collection/collection.dart";

List<Map<String, dynamic>> liste = [
{
"videoId": 1,
"videoName": "Test Video 1",
"duration": 300,
"createdTime": "1969-07-20 20:18:04Z",
"isWatch": 1,
},
{
"videoId": 2,
"videoName": "Test Video 2",
"duration": 500,
"createdTime": "1969-07-20 20:18:04Z",
"isWatch": 10,
},
{
"videoId": 2,
"videoName": "Test Video 2",
"duration": 500,
"createdTime": "1969-07-21 20:18:04Z",
"isWatch": 13,
},
{
"videoId": 2,
"videoName": "Test Video 2",
"duration": 500,
"createdTime": "1969-07-23 20:18:04Z",
"isWatch": 12,
},
{
"videoId": 2,
"videoName": "Test Video 2",
"duration": 500,
"createdTime": "1969-07-23 20:18:04Z",
"isWatch": 14,
}
];

_groupAndSum() {
Map groupByDay =
groupBy(liste, (obj) => DateTime.parse(obj['createdTime'].split(' ')[0])));

Map groupedAndSum = Map();

groupByDay.forEach((k, v) {
groupedAndSum[k] = {
'list': v,
'sumOfisWatch': v.fold(0, (prev, element) => prev + element['isWatch']),
};
});

print(groupByDay.toString());
print(groupedAndSum.toString());
}

输出将是:
flutter: {20: [{videoId: 1, videoName: Test Video 1, duration: 300, createdTime: 1969-07-20 20:18:04Z, isWatch: 1}, {videoId: 2, videoName: Test Video 2, duration: 500, createdTime: 1969-07-20 20:18:04Z, isWatch: 10}], 21: [{videoId: 2, videoName: Test Video 2, duration: 500, createdTime: 1969-07-21 20:18:04Z, isWatch: 13}], 23: [{videoId: 2, videoName: Test Video 2, duration: 500, createdTime: 1969-07-23 20:18:04Z, isWatch: 12}, {videoId: 2, videoName: Test Video 2, duration: 500, createdTime: 1969-07-23 20:18:04Z, isWatch: 14}]}

flutter: {20: {list: [{videoId: 1, videoName: Test Video 1, duration: 300, createdTime: 1969-07-20 20:18:04Z, isWatch: 1}, {videoId: 2, videoName: Test Video 2, duration: 500, createdTime: 1969-07-20 20:18:04Z, isWatch: 10}], sumOfisWatch: 11}, 21: {list: [{videoId: 2, videoName: Test Video 2, duration: 500, createdTime: 1969-07-21 20:18:04Z, isWatch: 13}], sumOfisWatch: 13}, 23: {list: [{videoId: 2, videoName: Test Video 2, duration: 500, createdTime: 1969-07-23 20:18:04Z, isWatch: 12}, {videoId: 2, videoName: Test Video 2, duration: 500, createdTime: 1969-07-23 20:18:04Z, isWatch: 14}], sumOfisWatch: 26}}

关于flutter - 如何从DART/Flutter中的数组中获取按天分组的每天的值总和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59990819/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com