我想使用以下条件对数组进行排序
我的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有投诉,
我需要获得最后位于的投诉ID的json对象,例如在对象中有很多complaintId: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
}
]
您可以使用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);