列表<映射<字符串,动态>> - 删除重复项但堆栈编号



我希望有人能帮助我。我正在尝试通过保留相同的描述来获取对象列表并堆叠所有重复项,但在需要时增加数量。

这是我目前拥有的:

测试数据:

List<Map<String, dynamic>> items = [
{'Description': 'Cheese', 'Quantity': 100, 'UoM': 'g'},
{'Description': 'Corn', 'Quantity': 150, 'UoM': 'g'},
{'Description': 'Cheese', 'Quantity': 52, 'UoM': 'g'},
];

我试图弄清楚的功能:

void stackDuplicates(items) {
final set = Set<String>();
int counter = 0;
// check the entire list only once
while (counter < items.length) {
items.forEach((item) {
// increase counter once a new item is checked
counter++;
// print the duplicate item for reference
//TODO: figure out how to check for duplicates without knowing the 'Description'
if (item.containsValue('Cheese')) {
print(item);
}
});
// return a list of unique descriptions
final newItems = items.where((item) {
return set.add(item['Description']);
}).toList();
// Print result
print(newItems);
}
}
}
stackDuplicates(items);

我似乎无法弄清楚如何组合重复数量的新列表。 此外,我正在尝试检查重复项,而不知道值是奶酪;值可以是任何东西。

任何协助将不胜感激。

编辑:对不起,我忘了提,如果 UoM 不同,请不要堆叠它们。

1( 堆栈到Map其中keyDescription-UoM字段组成

2(如果这样的密钥存在于Map只需累积Quantity

3( 将映射值作为列表返回

List<dynamic> stackDuplicates(items) {
Map<String, dynamic> uniqueItems = {};
for (Map item in items) {
final key = '${item["Description"]}-${item["UoM"]}';
(uniqueItems[key] == null)
? uniqueItems[key] = item
: uniqueItems[key]['Quantity'] += item['Quantity'];
}
return uniqueItems.values.toList();
}

List<Map<String, dynamic>> items = [
{'Description': 'Cheese', 'Quantity': 100, 'UoM': 'g'},
{'Description': 'Corn', 'Quantity': 150, 'UoM': 'g'},
{'Description': 'Cheese', 'Quantity': 52, 'UoM': 'g'},
];
final stackedItems = stackDuplicates(items);
print(stackedItems);

请根据分组规则随意更改key值。

最新更新