I have an array of logs that have the following structure let’s say:
LogItems = [
{
description: "I am the first log";
timestamp: "2023-02-20T20:15:43.2357511Z"
},
{
description: "I am the fourth log";
timestamp: "2023-02-20T21:20:43.2357511Z"
},
{
description: "I am the second log";
timestamp: "2023-01-20T20:10:43.2357511Z"
},
{
description: "I am the third log";
timestamp: "2023-01-20T20:10:43.2357511Z"
}
];
Now, I want to render this data in a different react component.
I want to show this list as described below:
20 Jan 2023
8:10:PM
I am the second log
I am the third log
20 Feb 2023
8:15 PM
I am the first log
9:20 PM
I am the fourth log
Should I create a new object literal from the logs array to create a nested array similar to the view I create or can I directly render this data in JSX in the desired view?
I am new to react so, any suggestions would be really helpful.
2
Answers
First of all you should group you logs by day, the format shoud be like this
2023-01-20
.Then group your logs by time, the format should be like this
20:10
.Your final array should be something like this:
This is the code:
you can use
reduce
to group the array into an object grouped by date and time. I have used 2 helper functions to format the date and time. Since you need January first I first sorted the array by epochIn react you can use nested map calls to do the nested rendering of the object.
Object.entries
is used to convert the object to an array of[key,value]
pairs so that I can callmap
on it. Also use a unique value for thekey
prop and refrain from using arrayindex
. Just used for simplicity here