Display nested array of objects in HTML table by iterating
P粉638343995
P粉638343995 2024-04-05 14:11:42
0
1
1514

I have the following input that contains an array of nested objects.

summary is the parent object array, run_type is the nested object array.

let input = {
      "summary": [
          {
              "name": "Release",
              "run_type": [
                {
                  "environment": "6nc",
                  "type": "QA1"
                },
                {
                  "environment": "3nc",
                  "type": "QA2"
                }
              ]
          }
      ]
  }

I want to display the following table. Since each summary has 2 run_type, the rowspan of the Name field is 2.

------------------------------------
   Name    | Environment | RunType |
------------------------------------
  Release  |     6nc     |  QA1    |
           |     3nc     |  QA2    |
------------------------------------

To display such a table statically, I can do this

<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>

Can someone tell me how to dynamically display this form? I tried this way but without success. The problem is that I can get the rowspan of the Name column to be 2 rows, but all the other columns are not being placed in both rows of the same Name section.

<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

reply all(1)
P粉431220279

The problem is that you are using a separate <tr> element to iterate over the run_typeenvironment and type. This causes the table structure to render incorrectly.

Here's how you can modify your code to achieve this:

<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>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template