移除列表中的重复项并获取其数量 Dart Flutter

huangapple go评论65阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年6月22日 00:13:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/76525267.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定