gpt4 book ai didi

flutter - Flutter/Dart组按日期列出

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

我有以下 map 列表,

[
{
"FullName":"Harry Potter",
"DateOfBirth": "2020/02/16",
"Department":"Branch Operation",
"BirthDay":"Friday"
},
{
"FullName":"John Wick",
"DateOfBirth": "2020/02/16",
"Department":"Finance",
"BirthDay":"Friday"
},
{
"FullName":"Solomon Kane",
"DateOfBirth":2020/02/19,
"Department":"Loan",
"BirthDay":"Monday"
}
]

我想操纵上面的数据,以使数据按其 DateOfBirth分组,以便结果看起来像这样。
[
{
"DateOfBirth": "2020/02/16",
"BirthDay": "Friday",
"Data":[
{
"FullName": "Harry Potter",
"Department":"Branch Operation",
},
{
"FullName":"John Wick",
"Department":"Finance",
}
]
},
{
"DateOfBirth": "2020/02/19",
"BirthDay": "Monday",
"Data":[
{
"FullName":"Solomon Kane",
"Department":"Loan"
}
]
},
]

在Javascript中,可以通过使用 reduce函数然后使用对象键映射来实现。
我也知道dart具有有用的软件包 collection

由于我不熟悉 Dart 和 Dart ,所以我不确定该怎么做。有人可以帮我吗?

谢谢

最佳答案

您可以使用fold并执行类似的操作

const data = [...];

void main() {
final value = data.fold(Map<String, List<dynamic>>(), (Map<String, List<dynamic>> a, b) {
a.putIfAbsent(b['DateOfBirth'], () => []).add(b);
return a;
}).values
.where((l) => l.isNotEmpty)
.map((l) => {
'DateOfBirth': l.first['DateOfBirth'],
'BirthDay': l.first['BirthDay'],
'Data': l.map((e) => {
'Department': e['Department'],
'FullName': e['FullName'],
}).toList()
}).toList();
}

还是这样,如果您想使用传播运算符,我不知道它是否可读性强。
 final result = data.fold({}, (a, b) => {
...a,
b['DateOfBirth']: [b, ...?a[b['DateOfBirth']]],
}).values
.where((l) => l.isNotEmpty)
.map((l) => {
'DateOfBirth': l.first['DateOfBirth'],
'BirthDay': l.first['BirthDay'],
'Data': l.map((e) => {
'Department': e['Department'],
'FullName': e['FullName'],
}).toList()
}).toList();

关于flutter - Flutter/Dart组按日期列出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62070559/

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