简体   繁体   中英

Populating data on a table in React

I have some nested data and i want to populate it in a table in react. As shown in the image, every method are in one row. How can i make a row for every method with its corresponding pages name? 在此处输入图像描述

const methods = [{
  id: "1",
  name: 'First',
  pagesName: [{
    name: 'Login',
    message: 'Login Notification Message',
    messageType: 'Warning'
  },
  {
    name: 'Edit',
    message:'Edit Notification Message',
    messageType: 'Info'
  }]
},
{
 id: "2",
  name: 'Second',
  pagesName: [{
    name: 'Admin',
    message: 'Admin Notification Message',
    messageType: 'Info'
  },
  {
   name: 'Edit',
   message: 'Edit Notification Message',
   messageType: 'Warning'
}
]}
]

Table

<tbody>
   {methods.map((p, key) => {
       return (
           <tr>
           <td>{key}</td>
           <td>{p.name}</td>
           {p.pagesName.map((n, key) => {
           return (
              <>
              <td>{n.name}</td>
              <td>{n.message}</td>
              <td>{n.messageType}</td>
              </>
            )
            })}
           </tr>
           )})
           }
   </tbody>

Use Array.map() like this: https://jsfiddle.net/Lc3m08dn/58/

<table>
    <thead>
        <tr>
            <th>ID</th>
            <th>Name</th>
            <th>PagesName</th>
            <th>Message</th>
            <th>messageType</th>
        </tr>
    </thead>
    {methods.map(method => (
        <tbody>
            <tr>
                <td rowspan={method.pagesName.length + 1}>{method.id}</td>
                <td rowspan={method.pagesName.length + 1}>{method.name}</td>
            </tr>
            {method.pagesName.map(page => (
                <tr>
                    <td>{page.name}</td>
                    <td>{page.message}</td>
                    <td>{page.messageType}</td>
                </tr>
            ))}
        </tbody>
    ))}
</table>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM