Anand
Anand

Reputation: 391

How to render nested elements in react

I am trying to render different db tables as html tables in react. Issue here is that the number of columns in each table is different. In my component i am recieving header data alongwith full table data in JSON format.

for Eg.


For table #1:
header data : ["A","B","c"]
table data : [{"A":1,"B":2,"c":3},{"A":4,"B":5,"c":6}]


For table #2:
header data : ["A","B"]
table data : [{"A":1,"B":2},{"A":4,"B":5}]

Now, something if in java i coulld have written something like:

for(Object i:tableData)
{
   for(Object j:headerData)
   {
      print(i[j])
   }

}

To ideally produce somthing like this :


for table #1:
1 2 3
4 5 6

for table #2:
1 2
3 4

But i'm not sure how to do this in react.

Till now i have coded something like this:


<table>
<thead><tr>{this.state.header.map(item=>{<th>{item}</th>})}</tr></thead>
<tbody>....</tbody>
</table>

Here, i'm able to get the required header like:


for table #1:
A B C

for table #2:
A B

But i'm not sure how to print the body elements. please give some appropriate suggestion, hint or link that may help me out.

Thanks

Upvotes: 1

Views: 593

Answers (1)

kiranvj
kiranvj

Reputation: 34107

You need to iterate object in each array element. Use Object.values Also check Object.keys and Object.entries for iterating object.

Something like this should work

<tbody>
{this.state.body.map((item)=> {
   return <tr> 
            { 
              Object.values(item).map(col => <td>{col}</td>)  
            } 
          </tr>
});}
</tbody>

Upvotes: 2

Related Questions