I have a LogsData in my react App:
const dailyLogsData = [
{
id: 1,
date_created: "01/15/2023",
time_updated: "15:53:05",
usage_notes: "sample notes",
maintenance_notes: "sample notes",
devices: [
{ device_name: "Port Engine", device_value: "0125", device_id: 1 },
{ device_name: "Generator", device_value: "0252", device_id: 2 },
{ device_name: "Water Maker", device_value: "0321", device_id: 3 },
{ device_name: "Fuel Engine", device_value: "", device_id: 4 },
{ device_name: "Radiator", device_value: "", device_id: 5 },
],
},
{
id: 2,
date_created: "01/16/2023",
time_updated: "15:53:05",
usage_notes: "sample notes",
maintenance_notes: "sample notes",
devices: [
{ device_name: "Port Engine", device_value: "0125", device_id: 1 },
{ device_name: "Generator", device_value: "0252", device_id: 2 },
{ device_name: "Water Maker", device_value: "0321", device_id: 3 },
{ device_name: "Fuel Engine", device_value: "0321", device_id: 4 },
{ device_name: "Radiator", device_value: "0321", device_id: 5 },
],
},
];
And I want to display each device name in a column and the device value should be in the row.
I have a simple solution, but I do not know how to get the device value for each device
const columns = dailyLogsData[0].devices.map((item) => ({
key: item.device_name.replace(/ /g, ""),
name: item.device_name.toUpperCase(),
}));
const columns2 = [
{ key: "id", name: "ID" },
{ key: "date_time", name: "DATE/TIME" },
{ key: "usage_notes", name: "USAGE NOTES" },
{ key: "maintenance_notes", name: "MAINTENANCE NOTES" },
...columns,
];
const rows = dailyLogsData.map((item) => ({
id: item.id,
date_time: `${item.date_created} | ${item.time_updated}`,
usage_notes: item.usage_notes,
maintenance_notes: item.maintenance_notes,
}));
return(
<DataGrid columns={columns2} rows={rows} />
)
Here is the output so far:
I am using this NPM Package for additional info: react-data-grid
>Solution :
You can create a multiple map function as below here:
const rows = dailyLogsData.map((item) => {
const row = {
id: item.id,
date_time: `${item.date_created} | ${item.time_updated}`,
usage_notes: item.usage_notes,
maintenance_notes: item.maintenance_notes,
};
item.devices.forEach((device) => {
row[device.device_name.replace(/ /g, "")] = device.device_value;
});
return row;
});
``