如何动态遍历嵌套对象数组生成带rowspan的HTML表格?
动态生成带rowspan的嵌套表格解决方案
问题背景
有如下嵌套结构的输入数据:
let input = { "summary": [ { "name": "Release", "run_type": [ { "environment": "6nc", "type": "QA1" }, { "environment": "3nc", "type": "QA2" } ] } ] }
需要生成如下格式的表格,其中Name列根据对应run_type的数量设置rowspan:
------------------------------------ Name | Environment | RunType | ------------------------------------ Release | 6nc | QA1 | | 3nc | QA2 | ------------------------------------
静态实现的代码是可行的,但动态生成时出现问题:虽然给Name列设置了rowspan=2,但其他列无法在同一分组下分成两行显示,错误的动态代码如下:
<table> <thead> <tr> <th>Vertical</th> <th>Environment</th> <th>RunType</th> </tr> </thead> <tbody> {input?.summary?.map((project, indx) => { return ( <tr> <td rowspan="2">{project?.name}</td> {project?.run_type?.map((runType, indx) => { return ( <> <td>{runType.environment}</td> <td>{runType.type}</td> </> ); })} </tr> ); })} </tbody> </table>
问题原因
错误代码的核心问题是:将同一个project下所有run_type对应的<td>都塞进了同一个<tr>中,导致生成的表格结构混乱,不符合HTML表格规范。正确的结构应该是每个run_type对应一行<tr>,仅第一行包含带rowspan的Name列,后续行省略该列的单元格。
正确实现代码
<table> <thead> <tr> <th>Name</th> <th>Environment</th> <th>RunType</th> </tr> </thead> <tbody> {input?.summary?.map((project, projIndex) => { const runTypes = project?.run_type || []; return runTypes.map((runType, rtIndex) => ( <tr key={`${projIndex}-${rtIndex}`}> {/* 仅第一个run_type行显示Name列,并设置rowspan */} {rtIndex === 0 && ( <td rowspan={runTypes.length}>{project.name}</td> )} <td>{runType.environment}</td> <td>{runType.type}</td> </tr> )); })} </tbody> </table>
代码说明
- 遍历
summary数组中的每个project,先获取其对应的run_type数组; - 遍历
run_type数组,为每个元素生成一行<tr>:- 当是第一个
run_type元素时,渲染带rowspan的Name单元格,rowspan的值为当前run_type数组的长度; - 后续的
run_type元素,只渲染Environment和RunType的单元格,省略Name列;
- 当是第一个
- 为每个
<tr>设置唯一的key,确保React渲染的稳定性。
内容的提问来源于stack exchange,提问作者Aren Trot
相关产品推荐
相关产品推荐

