英文:
Removing duplicate items in the list and getting their number Dart Flutter
问题
我有一个对象列表,我想去除重复项并将移除的项目数量添加到列表中的剩余项目中。
var data = [
{
name: "书",
qty: 1
},
{
name: "书",
qty: 1
},
{
name: "书",
qty: 1
},
{
name: "笔",
qty: 1
},
{
name: "笔",
qty: 1
},
];
结果应该是这样的
[{name: "书", qty: 3},{name: "笔",qty: 2}],
英文:
I have a list of objects and I want to remove duplicates and also add the number of removed items to the remaining item in the list.
var data = [
{
name: "book",
qty: 1
},
{
name: "book"
qty: 1
},
{
name: "book",
qty: 1
},
{
name: "pen",
qty: 1
},
{
name: "pen",
qty: 1
},
];
The result should be something like this
[{name: "book", qty: 3},{name: "pen",qty: 2}],
答案1
得分: 1
你可以通过使用collection库来实现这一点
通过输入以下代码来导入collection库
'import 'package:collection/collection.dart';'
然后使用groupby函数将项目分组在一起,这里是一个示例代码
var consolidatedData = groupBy(data, (obj) => obj['name'])
.values
.map((group) => {
'name': group.first['name'],
'qty': group.length,
})
.toList();
我希望这对你有帮助
英文:
You can do this by using the collection library
Import the collection library by typing
import 'package:collection/collection.dart';
and then use the groupby function to group the items together, Here's an example code
var consolidatedData = groupBy(data, (obj) => obj['name'])
.values
.map((group) => {
'name': group.first['name'],
'qty': group.length,
})
.toList();
I hope this helps
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论