I am using react JS to fetch some data from and API endpoint and then display it. I want to sort it by date and time before displaying it. Data looks like this when it's fetched:
{
"2021-03-09T07:47:24.897Z[UTC]": "Something happened",
"2021-03-09T07:48:12.256Z[UTC]": "Test event",
"2021-03-09T08:04:49.484Z[UTC]": "Warning",
"2021-03-09T07:08:15.714Z[UTC]": "Test event 2",
"2021-03-09T07:47:24.736Z[UTC]": "Something bad happened 2"
}
I cannot change this json structure. I need to sort this by date and time and display in this format YYYY-MM-DD h:mm:ss
My function to do this looks like this:
formatDate(obj) {
return Object.keys(obj).sort((a,b) => moment(a.obj).format('YYYY-MM-DD h:mm:ss') - moment(b.obj).format('YYYY-MM-DD h:mm:ss'))
}
Then I do the following to the fetched json object:
console.log(this.formatDate(json));
Doing so returns the following:
0: "2021-03-09T07:47:24.897Z[UTC]"
1: "2021-03-09T07:48:12.256Z[UTC]"
2: "2021-03-09T08:04:49.484Z[UTC]"
3: "2021-03-09T07:08:15.714Z[UTC]"
4: "2021-03-09T07:47:24.736Z[UTC]"
Returned dates are not sorted. How do I make sure these returned sorted?
Object.keys(obj).sort((a,b) => new Date(a.replace("\[UTC\]", "")) - new Date(b.replace("\[UTC\]", "")))