【发布时间】:2022-02-07 13:50:40
【问题描述】:
我有这些数据:
[
{ "name": "Eric", "origin": "Tristan da Cunha" },
{ "name": "Eric", "origin": "Tristan da Cunha" },
{ "name": "Adelaide", "origin": "Cayman Islands" }
]
有重复数据,如何在转换为列表之前将其删除?
【问题讨论】:
我有这些数据:
[
{ "name": "Eric", "origin": "Tristan da Cunha" },
{ "name": "Eric", "origin": "Tristan da Cunha" },
{ "name": "Adelaide", "origin": "Cayman Islands" }
]
有重复数据,如何在转换为列表之前将其删除?
【问题讨论】:
首先,为数据创建一个类,包括hashCode 和operator 覆盖。 toString override 是可选的,但会有所帮助:
class DataModel {
String? name;
String? origin;
DataModel({this.name, this.origin});
@override
int get hashCode => '$name, $origin'.hashCode;
// this will do the magic
@override
bool operator ==(Object other) {
return other is DataModel &&
name.toString() == other.name.toString() &&
origin.toString() == other.origin.toString();
}
@override
String toString() {
return "{name: '$name', origin: '$origin'}";
}
}
然后,在你的 Dart 代码中的任何地方:
import 'data_model.dart';
void main(List<String> arguments) {
// notice that Eric is duplicated in this entry
List<DataModel> filterData = [
DataModel(name: 'Eric', origin: "Tristan da Cunha"),
DataModel(name: 'Eric', origin: "Tristan da Cunha"),
DataModel(name: 'Adelaide', origin: "Cayman Islands"),
];
// toSet() will remove the redundancy, then convert it back to toList()
var removedDuplicatedDatas = filterData.toSet().toList();
print(removedDuplicatedDatas);
}
输出:
[{name: 'Eric', origin: 'Tristan da Cunha'}, {name: 'Adelaide', origin: 'Cayman Islands'}]
【讨论】:
按名称删除项目
final ids = uniqueLedgerList.map((e) => e["name"]).toSet();
uniqueLedgerList.retainWhere((x) => ids.remove(x["name"]));
log("Remove Duplicate Items--->$uniqueLedgerList");
【讨论】: