【发布时间】:2021-08-14 21:08:46
【问题描述】:
我有一个这样的列表:
var list = [
{
"type": "TypeA",
"subType": ["A1", "A2"]
},
{
"type": "TypeA",
"subType": ["A1"]
},
{
"type": "TypeB",
"subType": ["B1"]
},
{
"type": "TypeB",
"subType": ["B2", "B3"]
},
{
"type": "TypeC",
"subType": ["C1"]
}
];
如何使用旧列表中的独特元素创建新列表? 这是我想要的新列表:
newList = [
{
"type": "TypeA",
"subType": ["A1", "A2"]
},
{
"type": "TypeB",
"subType": ["B1", "B2", "B3"]
},
{
"type": "TypeC",
"subType": ["C1"]
}
];
编辑:所有答案都有效,但是,我不知道如何使用模型类将它们应用到我的实际项目中
所以请帮帮我,这是完整的代码:
class ListModel {
String type;
List<String> subType;
ListModel({this.type, this.subType});
}
void main() {
List<ListModel> list = [
ListModel(type: 'TypeA', subType: ['A1', 'A2']),
ListModel(type: 'TypeA', subType: ['A1']),
ListModel(type: 'TypeA', subType: []),
ListModel(type: 'TypeB', subType: ['B1']),
ListModel(type: 'TypeB', subType: ['B2', 'B3']),
ListModel(type: 'TypeC', subType: ['C1']),
];
//This is newList I want
List<ListModel> newList = [
ListModel(type: 'TypeA', subType: ['A1', 'A2']),
ListModel(type: 'TypeB', subType: ['B1', 'B2', 'B3']),
ListModel(type: 'TypeC', subType: ['C1']),
];
}
【问题讨论】: