flutter - Flutter: Group by Json 字符串的数组列表(按 ID)

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"}}]

我怎样才能 group by 和存档结果如下

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

回答1

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();
}

输出:

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

相似文章

最新文章