Flutter/Dart组列表(按日期)

tvz2xvvm  于 2023-09-28  发布在  Flutter
关注(0)|答案(2)|浏览(112)

我有以下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函数,然后使用Object键Map来实现。我还知道dart有一个有用的软件包叫做collection
因为我是新的 dart 和扑,我不知道该怎么做。有人能帮我吗?
谢谢

kognpnkq

kognpnkq1#

您可以使用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();
2q5ifsrm

2q5ifsrm2#

也有同样的问题。最佳解决方案:使用内部扩展。参见IterableExtension
更新pubspec.yaml并使用它。
https://api.flutter.dev/flutter/package-collection_collection/IterableExtension/groupListsBy.html

pubspec.yaml
...
dependencies:
  collection: any
final Map<String, List<ItemType>> result =
          data.groupListsBy((item) => item.timeField.year.toString());

相关问题