I'm trying to make a table from array of objects which have items, arrays and objects.
But mapping in typescript is so challenging for me.
I tried it this way, but I get no data rendered, just empty cells(by the way, all names of columns are already written)
<tr>
{items?.map((item, key: any) => {
return (
<>
{Object.keys(item).map((pole) => {
return (
<>
<td>{(item as any)[pole].request_date}</td>
<td>{(item as any)[pole].invoice_number}</td>
</>
);
// return console.log((item as any)[pole]);
})}
</>
);
})}
</tr>
etc.
Here you can see data from server, it's not full, but shows the main aim of task. Is it even real like I want
[
{
"_id": "63746fb7d938e62729d7727d",
"request_date": "2022-12-08T23:00:00.000Z",
"invoice_number": "invoice2",
"container": {
"container_number": "1",
"container_type": "H20",
"_id": "63746fb7d938e62729d7726d",
},
"importers": [
{
"name": "importer1",
"container": "63746fb7d938e62729d7726d",
"_id": "63746fb7d938e62729d77275",
},
{
"name": "importer2",
"container": "63746fb7d938e62729d7726d",
"_id": "63746fb7d938e62729d77276",
},
{
"name": "importer3",
"container": "63746fb7d938e62729d7726d",
"_id": "63746fb7d938e62729d77277",
}
]
},
]
CodePudding user response:
So I found the solution, it's a lot more easier than I thought.
First of all you need to make interface for object which you will map()
.
Than it's classic map into table cells.
interface Container = {
container_number: string;
container_type: string;
_id: string;
};
interface Importers = {
name: string;
_id: string;
};
interface Providers {
name: string;
_id: string;
};
interface TableProps {
data: {
_id: string;
request_date: string;
invoice_number: string;
container: Container;
importers: Importers[];
providers: Providers[];
}[];
}
Also if you have arrays or objects in your main object, you need to make interfaces for them all, as I show it.
and just iterate through array of objects
<tbody>
{data.map((item, key) => {
return (
<tr key={item._id}>
<td>{item.request_date}</td>
<td>{item.invoice_number}</td>
<td>{item.container.container_number}</td>
<td>
<table className="table-importers">
<tbody>
<tr>
{item.importers.map((importer) => {
return <td key={importer._id}>{importer.name}</td>;
})}
</tr>
</tbody>
</table>
</td>
<td>
<table className="table-importers">
<tbody>
<tr>
{item.providers.map((provider) => {
return <td key={provider._id}>{provider.name}</td>;
})}
</tr>
</tbody>
</table>
</td>
</tr>
);
})}
</tbody>
I'm not sure if it's a best practice, but it works 100%
Thank you !