The data that i recieve looks like this :
const myArray = [{
reason: 'vacation'
list: [{
name: 'John Doe'
startsAt: '2022-05-19'
endsAt: '2022-06-01'
},
{
name: 'Jenifer Doe'
startsAt: '2022-06-10'
endsAt: '2022-06-15'
}
],
},
{
reason: 'sick'
list: [{
name: 'Susan'
startsAt: '2022-05-20'
endsAt: '2022-05-21'
}]
}
]
The final result that i want to achieve is an table with that will look something like this :
=====================================================
| Name | Created at | Canceled at | Reason |
=====================================================
| John Doe | 2022-05-19 | 2022-06-01 | vacation |
-----------------------------------------------------
| Jenifer Doe | 2022-06-10 | 2022-06-15 | vacation |
-----------------------------------------------------
| Susan | 2022-05-20 | 2022-05-21 | sick |
This is my try to get the data that i need into my table
export const MyComponent: FunctionComponent = () => {
return (
<>
{myArray.map((data) => (
<tr>
<td>{data.reason}</td>
data.list.map((listData) => {
<td>{listData.name}</td>
<td>{listData.startsAt}</td>
<td>{listData.endsAt}</td>
})
</tr>
))}
</>
)
}
I think that map in map is not the solution here . Can someone give me a hand and explain me what is going on ?
CodePudding user response:
First, since it appears that you want each row in the table to be the elements in each list
property, you might consider flattening those arrays into a single array. Ideally, you want to get it into a format that more closely resembles the rows of the table, for example:
const myNewArray = [
{
name: "John Doe",
startsAt: "2022-05-19",
endsAt: "2022-06-01",
reason: "vacation",
},
{
name: "Jenifer Doe",
startsAt: "2022-06-10",
endsAt: "2022-06-15",
reason: "vacation",
},
{
name: "Susan",
startsAt: "2022-05-20",
endsAt: "2022-05-21",
reason: "sick",
},
];
This can be achieved, for example, by using Array.prototype.reduce() :
const myNewArray = myArray.reduce((newArray, item) => {
const reason = item.reason;
newArray = newArray.concat(
item.list.map((listItem) => ({ ...listItem, reason }))
);
return newArray;
}, []);
Then you can render the rows of the table using a single map:
<>
{myNewArray.map((data) => (
<tr>
<td>{data.name}</td>
<td>{data.startsAt}</td>
<td>{data.endsAt}</td>
<td>{data.reason}</td>
</tr>
))}
</>