Flutter:按 Id 按 Json 字符串的数组列表分组
Flutter: Group by Array List of Json String by 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"}}]
如何分组并归档如下结果
[{"attribute_id":1, "values":["#000000","#66cccc"]},{"attribute_id":2, "values":["#cd7d96"]}]
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]}]
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"}}]
如何分组并归档如下结果
[{"attribute_id":1, "values":["#000000","#66cccc"]},{"attribute_id":2, "values":["#cd7d96"]}]
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]}]