我是飞镖和飞镖的新手。我已经尝试过使用javascript的任何代码来解决它,但是它不起作用:(。
我想获取订单长度,但是我不想从destination.id获取相同的值。对这种情况有什么想法吗?可以使用库query.dart或其他任何方法来解决这种情况吗?
这是我的JSON数据。
{
"data": {
"shipments": [
{
"id": "1608",
"orders": [
{
"destination": {
"id": "979"
}
},
{
"destination": {
"id": "979"
}
},
{
"destination": {
"id": "1074"
}
},
{
"destination": {
"id": "1074"
}
},
{
"destination": {
"id": "1022"
}
},
{
"destination": {
"id": "1022"
}
},
]
},
{
"id": "1599",
"orders": [
{
"destination": {
"id": "979"
}
},
{
"destination": {
"id": "979"
}
},
{
"destination": {
"id": "1660"
}
},
{
"destination": {
"id": "1660"
}
},
]
}
]
}
}
答案 0 :(得分:1)
尝试:
var data = ... your JSON data ...;
List orders = data["data"]["shipments"]["orders"];
var uniqueIds = orders.map((o) => o["destination"]["id"]).toSet();
var uniqueCount = uniqueIds.length;
这将在Set
中收集唯一ID,以确保重复副本被忽略并计数。
答案 1 :(得分:1)
您还可以使用收集包中的groupBy函数。它将整齐地将所有重复项收集在以id为键的列表中。
import 'package:collection/collection.dart';
List orders = data["data"]["shipments"]["orders"];
var newMap = groupBy(orders, (obj) => obj['destination']['id']);
var length = newMap.length;
print("$newMap, length: $length");
输出:
{
979: [
{destination: {id: 979
}
},
{destination: {id: 979
}
}
],
1074: [
{destination: {id: 1074
}
},
{destination: {id: 1074
}
}
],
1022: [
{destination: {id: 1022
}
},
{destination: {id: 1022
}
}
]
},
length: 3