我有一个包含嵌套对象数组的以下input。
summary是父级对象数组,run_type是嵌套的对象数组。
let input = {
"summary": [
{
"name": "Release",
"run_type": [
{
"environment": "6nc",
"type": "QA1"
},
{
"environment": "3nc",
"type": "QA2"
}
]
}
]
}
我想要显示如下表格。由于每个summary有2个run_type,所以Name字段的rowspan为2。
------------------------------------
Name | Environment | RunType |
------------------------------------
Release | 6nc | QA1 |
| 3nc | QA2 |
------------------------------------
要静态显示这样的表格,我可以这样做
<table>
<thead>
<tr>
<th>Vertical</th>
<th>Environment</th>
<th>RunType</th>
</tr>
</thead>
<tbody>
<tr>
<td rowspan="2">Release</td>
<td>6nc</td>
<td>QA1</td>
</tr>
<tr>
<td>3nc</td>
<td>QA2</td>
</tr>
</tbody>
</table>
请问有人可以告诉我如何动态显示这个表格吗?我尝试过这种方式,但是没有成功。问题是我可以将Name列的rowspan设为2行,但是其他所有列都没有被放置在同一Name部分的两行中。
<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> Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
问题出在于您使用了一个单独的
<tr>元素来迭代run_type环境和类型。这会导致表格结构的渲染不正确。以下是您可以修改代码以实现此目的的方法:
<tbody> {input?.summary?.map((project, projectIndex) => ( <> {project?.run_type?.map((runType, runTypeIndex) => ( <tr key={`${projectIndex}-${runTypeIndex}`}> {runTypeIndex === 0 ? ( <td rowspan={project.run_type.length}>{project.name}</td> ) : null} <td>{runType.environment}</td> <td>{runType.type}</td> </tr> ))} </> ))} </tbody>