如何减少List依赖于id(重复),但保持合并子数组的颤振



在我的代码中,我需要减少一个列表取决于id重复,但保持合并子数组Flutter。

具体来说,我有1个列表的项目具有相同的id,但不同的和选项。我需要减少具有不同id和选项的列表的数量,以便从具有相同id的项目中合并。

源对象:

"optionGroups": [
{
"name": "CHỌN SIZE",
"optionGroupId": 1557,
"options": [
{
"name": "Size L",
"price": 12.0,
"optionId": 6734
}
]
},
{
"name": "TOPPING",
"optionGroupId": 1558,
"options": [
{
"name": "Đường Nâu",
"price": 12.0,
"optionId": 6732
}
]
},
{
"name": "TOPPING",
"optionGroupId": 1558,
"options": [
{
"name": "Thạch Dừa",
"price": 8.0,
"optionId": 6731
}
]
}
]

和预期结果。

"optionGroups": [
{
"name": "CHỌN SIZE",
"optionGroupId": 1557,
"options": [
{
"name": "Size L",
"price": 12.0,
"optionId": 6734
}
]
},
{
"name": "TOPPING",
"optionGroupId": 1558,
"options": [
{
"name": "Đường Nâu",
"price": 12.0,
"optionId": 6732
},
{
"name": "Thạch Dừa",
"price": 8.0,
"optionId": 6731
}
]
},
]

谢谢你的回答!

有一种方法:

final filteredItems = <Map<String,dynamic>>[];
for (final item in items) {
int? index;
Map<String,dynamic> newItem = item;
for (final filteredItem in filteredItems) {
if (filteredItem['optionGroupId'] == item['optionGroupId']) {
index = filteredItems.indexOf(filteredItem);
newItem['options'].addAll(filteredItem['options']);
}
}
if (index == null) {
filteredItems.add(item);
} else {
filteredItems[index] = item;

}
}