I have two arrays of objects. The first array has the column names, the second has the table data. I want to display the data respectively. One of the objects contains 3 key-values, they display in the first three TableRows and I want them to display dynamically in column number three and four.
I want to display the second object of the rows array in columns three and four.
const columns = [
{id: 1, one: "one", two: "two", three: "three", four: "four"}
]
const rows = [
{id: 1, title: "dog", age: "2", name: "Buzzy"}
{id: 2, item: "laptop", data: "something", year: "1980"}
]
<table>
<thead>
{columns.map((data) => (
<tr key={data.id}>
{Object.entries(data).map(([key, value]) => (
<th key={key}>{value}</th>
))}
</tr>
</thead>
<tbody>
{rows.map((data) => (
<tr key={data.id}>
{Object.entries(data).map(([key, value]) => (
<td key={key}>{value}</td>
))}
</tr>
))}
</tbody>
</table>
2
Answers
Try this:
I’m not sure if you are able to change the columns data structure, or you are just receiving them like that.
In any case, I’m assuming we are on the second case, so my first suggestion is to manipulate that data to make it easier to handle. when rendering.
newColumns
is an array of objects that represent each column.accesorKey
is the the key we will use to match a row field to a specific column.header
is the header label of that column.newRows
is an array of rows, where each field represent a column accesorKey.