React表格渲染问题:基于嵌套数据结构生成表头与单元格
Rendering a React Table from Nested Data Structures
Got it, let's solve this problem step by step. You have nested data where each top-level object represents a column (with its header as cell_name), and the step_data array holds the row values for that column. Here's how to turn that into a clean React table:
First, Let's Define the Component
We'll create a reusable component that takes your data as a prop. I'll use your sample data (completed for clarity) and show how to map it to a table:
import React from 'react'; const NestedDataTable = ({ data }) => { // Extract table headers from each top-level object's cell_name const tableHeaders = data.map(column => column.cell_name); // Calculate the number of rows needed (use longest step_data array to avoid missing rows) const totalRows = Math.max(...data.map(column => column.step_data.length)); return ( <table style={{ borderCollapse: 'collapse', width: '100%' }}> {/* Table Header */} <thead> <tr> {tableHeaders.map((header, idx) => ( <th key={data[idx].cell_id} style={{ border: '1px solid #ddd', padding: '8px', backgroundColor: '#f2f2f2' }} > {header} </th> ))} </tr> </thead> {/* Table Body */} <tbody> {Array.from({ length: totalRows }).map((_, rowIndex) => ( <tr key={rowIndex}> {data.map((column) => ( <td key={`${column.cell_id}-${rowIndex}`} style={{ border: '1px solid #ddd', padding: '8px', textAlign: 'left' }} > {/* Display the 'name' property from step_data; adjust to your needs */} {column.step_data[rowIndex]?.name || '-'} </td> ))} </tr> ))} </tbody> </table> ); }; // Example usage with your data const sampleData = [ { "cell_id": 1, "step_data": [ { "width": 1920, "name": "bruce" }, { "width": 2236, "name": "ben" } ], "cell_name": "Boys Names" }, { "cell_id": 2, "step_data": [ { "width": 1920, "name": "grace" }, { "width": 2236, "name": "emma" } ], "cell_name": "Girls Names" } ]; // To use the component: <NestedDataTable data={sampleData} /> export default NestedDataTable;
Key Breakdown:
- Extracting Headers: We map over your top-level data array to pull out each
cell_nameand use those as our table headers. - Calculating Rows: We find the length of the longest
step_dataarray to ensure we don't miss any rows (even if some columns have fewer entries). - Rendering Rows: We create an array of rows using
Array.from({ length: totalRows }). For each row, we loop through each column and pull the corresponding entry fromstep_data. The optional chaining (?.) and fallback (|| '-') handle cases where a column doesn't have data for that row. - Styling: Added basic inline styles to make the table readable—you can replace this with your own CSS classes.
Customization Tips:
- If you want to display multiple properties from
step_data(likewidthandname), update the<td>content:{column.step_data[rowIndex] ? `${column.step_data[rowIndex].name} (Width: ${column.step_data[rowIndex].width})` : '-'} - For better performance (if your data changes frequently), consider memoizing the headers and rows using
useMemo. - If your
step_dataarrays are guaranteed to be the same length, you can simplifytotalRowstodata[0].step_data.length.
内容的提问来源于stack exchange,提问作者marcuspetty
相关产品推荐
相关产品推荐

