简体   繁体   中英

Flutter/Dart how to groupBy list of maps

I have this list of maps.

[
    {title: 'Avengers', release_date: '10/01/2019'},
    {title: 'Creed', release_date: '10/01/2019'}
    {title: 'Jumanji', release_date: '30/10/2019'},
]

The package collection<\/a> implements the groupBy<\/code> function.

import "package:collection/collection.dart";

main(List<String> args) {
  var data = [
    {"title": 'Avengers', "release_date": '10/01/2019'},
    {"title": 'Creed', "release_date": '10/01/2019'},
    {"title": 'Jumanji', "release_date": '30/10/2019'},
  ];


  var newMap = groupBy(data, (Map obj) => obj['release_date']);

  print(newMap);
}

If you have Dart 2.7<\/strong> , you can extend<\/em> Iterable<\/code> to add a useful groupBy<\/code> method:

extension Iterables<E> on Iterable<E> {
  Map<K, List<E>> groupBy<K>(K Function(E) keyFunction) => fold(
      <K, List<E>>{},
      (Map<K, List<E>> map, E element) =>
          map..putIfAbsent(keyFunction(element), () => <E>[]).add(element));
}

This is a method naively implemented (in case you don't want to use the groupBy function from the collections package):

List<Map<String, List<Map<String, String>>>> MapByKey(String keyName, String newKeyName, String keyForNewName, List<Map<String,String>> input) {
  Map<String, Map<String, List<Map<String, String>>>> returnValue = Map<String, Map<String, List<Map<String, String>>>>();
  for (var currMap in input) {
    if (currMap.containsKey(keyName)) {
      var currKeyValue = currMap[keyName];
      var currKeyValueForNewName = currMap[keyForNewName];
      if (!returnValue.containsKey(currKeyValue)){
        returnValue[currKeyValue] = {currKeyValue : List<Map<String, String>>()};  
      }
      returnValue[currKeyValue][currKeyValue].add({newKeyName : currKeyValueForNewName});
    }
  }
  return returnValue.values.toList();
}

void main() {
    var test = [
    {"title": 'Avengers', "release_date": '10/01/2019'},
    {"title": 'Creed', "release_date": '10/01/2019'},
    {"title": 'Jumanji', "release_date": '30/10/2019'},
  ];

  var testMapped = MapByKey("release_date", "name", "title", test);

  print("$testMapped");
}

The output is:

[
    {
        10/01/2019: [
            {name: Avengers
            },
            {name: Creed
            }
        ]
    },
    {
        30/10/2019: [
            {name: Jumanji
            }
        ]
    }
]

Using the supercharged<\/a> package, you'd write it like this:

List list = [
  { title: 'Avengers', release_date: '10/01/2019' },
  { title: 'Creed', release_date: '10/01/2019' }
  { title: 'Jumanji', release_date: '30/10/2019' },
];

final map = list.groupBy<String, Map>((item) => 
  item['release_date'],
  valueTransform: (item) => item..remove('release_date'),
);

To add to the accepted answer if you come arcross this, In flutter 2, you will Get an error, as i got.

The operator '[]' isn't defined for the type 'dynamic Function(dynamic)'
extension UtilListExtension on List{
  groupBy(String key) {
    try {
      List<Map<String, dynamic>> result = [];
      List<String> keys = [];

      this.forEach((f) => keys.add(f[key]));

      [...keys.toSet()].forEach((k) {
        List data = [...this.where((e) => e[key] == k)];
        result.add({k: data});
      });

      return result;
    } catch (e, s) {
      printCatchNReport(e, s);
      return this;
    }
  }
}

I don't know why no one has mentioned that with how basic built-in functions and methods you can achieve it, like:

main() {
  List<Map> data = [
    {'title': 'Avengers', 'release_date': '10/01/2019'},
    {'title': 'Creed', 'release_date': '10/01/2019'},
    {'title': 'Jumanji', 'release_date': '30/10/2019'},
  ];

  // Loop through empty {} map and check if the release date exists, if not
  // add as the key and empty list as the value, then fill the list with element
  // itself, removing 'release_date' before adding. Then you can map the map
  // to a list of maps.
  List result = data
      .fold({}, (previousValue, element) {
        Map val = previousValue as Map;
        String date = element['release_date'];
        if (!val.containsKey(date)) {
          val[date] = [];
        }
        element.remove('release_date');
        val[date]?.add(element);
        return val;
      })
      .entries
      .map((e) => {e.key: e.value})
      .toList();

  print(result);
}

Many different kinds of transformations can applies to specified data sequence.

import 'package:queries/collections.dart';

main(List<String> args) {
  var c = Collection([
    {"title": 'Avengers', "release_date": '10/01/2019'},
    {"title": 'Creed', "release_date": '10/01/2019'},
    {"title": 'Jumanji', "release_date": '30/10/2019'},
  ]);

  var result = c
      .groupBy$1((e) => e["release_date"], (e) => {"title": e["title"]})
      .toDictionary$1((e) => e.key, (e) => e.toList());

  var keyValuePairs = result.toList();
  print("List of key and value pairs:");
  print(keyValuePairs);

  var map = result.toMap();
  print("Map of transformed elements:");
  print(map);

  var result2 = c
      .groupBy((e) => e["release_date"])
      .select((e) => {"${e.key}": e.toList()});

  print("Map of original elements:");
  print(result2.toList());
}

Results:

List of key and value pairs:
[10/01/2019 : [{title: Avengers}, {title: Creed}], 30/10/2019 : [{title: Jumanji}]]
Map of transformed elements:
{10/01/2019: [{title: Avengers}, {title: Creed}], 30/10/2019: [{title: Jumanji}]}
Map of original elements:
[{10/01/2019: [{title: Avengers, release_date: 10/01/2019}, {title: Creed, release_date: 10/01/2019}]}, {30/10/2019: [{title: Jumanji, release_date: 30/10/2019}]}]

It may not be the best solution. But it can give you an idea

List arrayData = [
  {"name": 'John', "gender": 'male'},
  {"name": 'James', "gender": 'male'},
  {"name": 'Mary', "gender": 'female'}
];

Retrieve list ​​by gender:

List males = arrayData.where((o) => o['gender'] == "male").toList();
List females = arrayData.where((o) => o['gender'] == "female").toList();

Make new map with desired format:

List result = [
  {
    "male": males.map((f) => {"name": f['name']}).toList()
  },
  {
    "female": females.map((f) => {"name": f['name']}).toList()
  }
];

print:

debugPrint('${result}');

result:

[{male: [{name: John}, {name: James}]}, {female: [{name: Mary}]}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM