I have a nested array, and want to convert it into a table in React.
For example, my data is represented as:
data = [[a,b,c], [d,e,f], [g, h, i]]
and I would like to represent it as a table in React that looks something like:
a d g
b e h
c f i
with each entry in the data list as a column, and the first entry in each nested list (a, d, and g in my case) as headers. I have been trying to use nested map functions, but have been unsuccessful
Array.map() is your new best friend!
First though, it is much easier to do rows first, then columns, so you'll want to reformat your data from
[[a,b,c], [d,e,f], [g, h, i]]
to
[[a,d,g], [b,e,h], [c,f,i]]
After you've done this, you can use map() to iterate over each child array. Each child array will be its own <tr />. Inside of the <tr /> you can iterate over each element in the child array, placing each inside of a <td />.
The result might look something like this
// The data
const data = [[a,d,g], [b,e,h], [c,f,i]]
// Inside the component
<table>
{
data.map((row, index) => {
return (
<tr key={index}>
{
row.map((cell, index) => {
return <td key={index}>{cell}</td>
})
}
</tr>
)
})
}
</table>
Hopefully this helps!