You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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:

  1. Extracting Headers: We map over your top-level data array to pull out each cell_name and use those as our table headers.
  2. Calculating Rows: We find the length of the longest step_data array to ensure we don't miss any rows (even if some columns have fewer entries).
  3. 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 from step_data. The optional chaining (?.) and fallback (|| '-') handle cases where a column doesn't have data for that row.
  4. 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 (like width and name), 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_data arrays are guaranteed to be the same length, you can simplify totalRows to data[0].step_data.length.

内容的提问来源于stack exchange,提问作者marcuspetty

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:30:28