透過迭代顯示嵌套的物件數組在HTML表格中
P粉638343995
P粉638343995 2024-04-05 14:11:42
0
1
1388

我有一個包含巢狀物件陣列的以下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>

P粉638343995
P粉638343995

全部回覆(1)
P粉431220279

問題出在於您使用了一個單獨的<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>
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!