根据特定条件,使用jq删除JSON数组中的重复对象



我有以下数据,我希望根据"run"键的重复值删除整个对象,同时保留具有最大"startTime"编号的对象:

{
"data": {
"results": [
{
"event": {
"biking": {
"startTime": 12,
"id": "a",
"run": "x"
}
},
"displayName": "Alex"
},
{
"event": {
"biking": {
"startTime": 10,
"id": "b",
"run": "x"
}
},
"displayName": "Adam"
},
{
"event": {
"biking": {
"startTime": 11,
"id": "c",
"run": "y"
}
},
"displayName": "Aaron"
}
]
}
}

我一直试图用jq欺骗unique,但无法完全得到我想要的。我的预期结果是:

{
"data": {
"results": [
{
"event": {
"biking": {
"startTime": 12,
"id": "a",
"run": "x"
}
},
"displayName": "Alex"
},
{
"event": {
"biking": {
"startTime": 11,
"id": "c",
"run": "y"
}
},
"displayName": "Aaron"
}
]
}
}

我尝试使用unique,因为我只想保留每个"run":id中的1个,在较大的列表中,我可能有三个x、两个y和四个z。在这种情况下,我想在最大的"startTime"的基础上保留一个xyz

这里有一个简单的jq解决方案:

.data.results |=
(group_by(.event.biking.run)
| map(max_by(.event.biking.startTime)))

它使用CCD_;运行";,然后CCD_ 15来选择期望的事件。

  • 以下是如何使用reducer来完成

const input = {
"data": {
"results": [{
"event": {
"biking": {
"startTime": 12,
"id": "a",
"run": "x"
}
},
"displayName": "Alex"
},
{
"event": {
"biking": {
"startTime": 10,
"id": "b",
"run": "x"
}
},
"displayName": "Adam"
},
{
"event": {
"biking": {
"startTime": 11,
"id": "c",
"run": "y"
}
},
"displayName": "Aaron"
}
]
}
};
const output = {
data: {}
};
output.data.results = Object.values(input.data.results.reduce((r, o) => {
r[o.event.biking.run] =
(r[o.event.biking.run] &&
r[o.event.biking.run].event.biking.startTime > o.event.biking.startTime) ? r[o.event.biking.run] : o
return r
}, {}));
console.log(output);

  • 学分->https://stackoverflow.com/a/56901839/8057127

这将适用于

const result = [
...new Map(
obj.data.results.map((item) => [item["event"]["biking"]["run"], item])
).values()
];

演示

这是基于helprjs removeDuplicates。

最新更新