Home > Mobile >  Flutter: Group by Array List of Json String by Id
Flutter: Group by Array List of Json String by Id

Time:05-19

String jsonString = [{"color":"#000000","quantity":"100","price":"999","attribute":{"id":1,"name":"SIZE"}},{"color":"#cd7d96","quantity":"40","price":"555","attribute":{"id":2,"name":"FABRIC"}},{"color":"#66cccc","quantity":"500","price":"1000","attribute":{"id":1,"name":"SIZE"}}]

How can I group by and archive results as below

[{"attribute_id":1, "values":["#000000","#66cccc"]},{"attribute_id":2, "values":["#cd7d96"]}]

CodePudding user response:

import 'dart:convert';

const raw = 
'''
  [{"color":"#000000","quantity":"100","price":"999","attribute":{"id":1,"name":"Iphone 12"}},{"color":"#cd7d96","quantity":"40","price":"555","attribute":{"id":2,"name":"SAMSUNG"}},{"color":"#66cccc","quantity":"500","price":"1000","attribute":{"id":1,"name":"OPPO"}}]
''';

typedef JMap = Map<String, dynamic>;
typedef LJMap = List<JMap>;

void groupById() {
  final data = (jsonDecode(raw) as List).cast<JMap>();
  var result = <JMap>[];
  data.map<int>((m) => m['attribute']['id']).toSet().forEach((e) { 
    result.add({
      'attribute_id': e, 
      'values': data.where((m) => m['attribute']['id'] == e).map((m) => m['color']).toList(),
    });
  });

  print(result);
}

void main(List<String> args) {
  groupById();
}

Output:

[{attribute_id: 1, values: [#000000, #66cccc]}, {attribute_id: 2, values: [#cd7d96]}]
  • Related