skip to Main Content

I have a nested array in html table. Am able to display the table. However, i have a problem with inserting headers to the nested arrays columns.

Below is the code:
table.js

const Table= college?.map((item =>   
      <tr >
       <td> {item.department.map((item,i) => (
                  <tr>
                    <td>{item.studentName}</td>
                    <td>{item.subject}</td>
                    <td>{item.daysClassattended}</td>
                  </tr>                        
             ))} 
       </td>                     
     </tr>
    ));
         return (
    <div>
      <table>
        <thead>
          <tr>
            <th>Student Name </th>
            <th>Subject </th>
            <th>Days Attended Classes</th>
          </tr>
        </thead>
        <tbody>{Table}</tbody>
      </table>;
    </div>

What is the best way to insert headers into the nested array table? Thanks in advance

2

Answers


  1. If you’re just looking to list all the students together without distinguishing their departments, then flatMap is an option:

      const Table = college?.flatMap((item =>   
        item.department.map((item,i) => (
          <tr>
            <td>{item.studentName}</td>
            <td>{item.subject}</td>
            <td>{item.daysClassattended}</td>
          </tr>                        
        ))
      ));
    
    Login or Signup to reply.
  2. To insert headers to the nested array columns in the HTML table, you can modify the code as follows:

    const Table = college?.map((item) => {
      return (
        <>
          <tr>
            <th colSpan="3">{item.departmentName}</th>
          </tr>
          <tr>
            <th>Student Name</th>
            <th>Subject</th>
            <th>Days Attended Classes</th>
          </tr>
          {item.department.map((student, i) => (
            <tr key={i}>
              <td>{student.studentName}</td>
              <td>{student.subject}</td>
              <td>{student.daysClassattended}</td>
            </tr>
          ))}
        </>
      );
    });
    
    return (
      <div>
        <table>
          <tbody>{Table}</tbody>
        </table>
      </div>
    );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search