按日期对JSON对象数组进行排序

时间:2020-01-31 06:21:31

标签: javascript arrays json sorting

我通过API调用获得了这个对象的JSON数组,我想按日期对它进行排序。但是日期格式是ISO格式,所以我是javascript的新手,所以我不知道如何转换然后排序。

  "statuses": [
    {
      "date": "2020-01-31T05:57:32.143Z",
      "status": "Awaiting Pickup"
    },
    {
      "date": "2020-01-30T07:55:08.033Z",
      "status": "Dispatched"
    },
    {
      "date": "2020-01-18T07:55:08.033Z",
      "status": "Parcel Assigned to Rider for Delivery"
    },
    {
      "date": "2020-01-12T07:55:08.033Z",
      "status": "Delivered"
    },
    {
      "date": "2020-01-24T07:55:08.033Z",
      "status": "Returned"
    }
  ],
}

1 个答案:

答案 0 :(得分:3)

使用sort。要进行转换,您可以使用new Date()

var obj={ "statuses": [
    {
      "date": "2020-01-31T05:57:32.143Z",
      "status": "Awaiting Pickup"
    },
    {
      "date": "2020-01-30T07:55:08.033Z",
      "status": "Dispatched"
    },
    {
      "date": "2020-01-18T07:55:08.033Z",
      "status": "Parcel Assigned to Rider for Delivery"
    },
    {
      "date": "2020-01-12T07:55:08.033Z",
      "status": "Delivered"
    },
    {
      "date": "2020-01-24T07:55:08.033Z",
      "status": "Returned"
    }
  ],
}
obj.statuses.sort((a,b)=>new Date(a.date)-new Date(b.date))
console.log(obj)