我想使用以下条件对数组进行排序
我的json对象:
[
{
"id": 1,
"status": true,
"time": "2018-03-05T10:24:15.000Z",
"complaintId": 1
},
{
"id": 2,
"status": true,
"time": null,
"complaintId": 1
},
{
"id": 3,
"status": true,
"time": "2018-03-05T10:53:14.000Z",
"complaintId": 2
},
{
"id": 6,
"status": false,
"time": "2018-03-05T11:58:45.000Z",
"complaintId": 1
},
{
"id": 7,
"status": true,
"time": "2018-03-05T12:11:53.000Z",
"complaintId": 1
},
{
"id": 8,
"status": false,
"time": "2018-03-05T13:23:13.000Z",
"complaintId": 2
},
{
"id": 9,
"status": true,
"time": "2018-03-05T08:17:18.000Z",
"complaintId": 3
},
{
"id": 10,
"status": true,
"time": "2018-03-05T12:32:08.000Z",
"complaintId": 2
}
]
我在json中有投诉,
我需要获得带有投诉的时间的json对象,例如在对象中有很多的投诉ID:1。
我只需要获得最后有抱怨的内容。
我的预期输出:
[
{
"id": 7,
"status": true,
"time": "2018-03-05T12:11:53.000Z",
"complaintId": 1
},
{
"id": 9,
"status": true,
"time": "2018-03-05T08:17:18.000Z",
"complaintId": 3
},
{
"id": 10,
"status": true,
"time": "2018-03-05T12:32:08.000Z",
"complaintId": 2
}
]
答案 0 :(得分:4)
您可以使用array#reduce
并为每种类型的complaintId
检查它是否没有time
值,然后更新它或者对象是否有时间值然后更新对应于complaintId
的值。
var data = [ { "id": 1, "status": true, "time": "2018-03-05T10:24:15.000Z", "complaintId": 1 }, { "id": 2, "status": true, "time": null, "complaintId": 1 }, { "id": 3, "status": true, "time": "2018-03-05T10:53:14.000Z", "complaintId": 2 }, { "id": 6, "status": false,"time": "2018-03-05T11:58:45.000Z", "complaintId": 1 }, { "id": 7, "status": true, "time": "2018-03-05T12:11:53.000Z", "complaintId": 1 }, { "id": 8, "status": false, "time": "2018-03-05T13:23:13.000Z", "complaintId": 2 }, { "id": 9, "status": true, "time":"2018-03-05T08:17:18.000Z", "complaintId": 3 }, { "id": 10, "status": true, "time": "2018-03-05T12:32:08.000Z", "complaintId": 2 } ],
result = Object.values(data.reduce((r,o) => {
if(!r[o.complaintId] || !r[o.complaintId].time || o.time)
r[o.complaintId] = {...o};
return r;
},{}))
.sort((a,b) => a.id - b.id);
console.log(result);