mr.abdo
mr.abdo

Reputation: 485

How to iterate an array of objects through each object element?

I'm trying to iterate an array of objects to display each object element in a table.

Thats my array:

     list: [
                {header: ['id', 'name', 'date', 'verified']},
                {body: [1, 'abc', '26-10-2019', true]}
            ]

I want to render a table in a vertical position like this: enter image description here

That's how I'm trying to do:

const render = list.map((result, idx) => (
            <tr key={idx}>
                <td>{result.header}</td>                
                <td>{result.body}</td>                
            </tr>
        ))

But the result is

<tr>
   <td>id name date verified</td>
</tr>
<tr>
   <td>1 abc 26-10-2019 true</td>
</tr>

Upvotes: 0

Views: 59

Answers (2)

Shridhar Sharma
Shridhar Sharma

Reputation: 2387

You need to repeat the whole table, like this

const render = list[0].header.map((name, i) => <tr key={i}>
                <td>{name}</td>
                <td>{String(list[1].body[i])}</td>
            </tr>)

Upvotes: 4

Nikko Khresna
Nikko Khresna

Reputation: 1009

try:

      const render = list.map((result, idx) => (
        <tr key={idx}>
            <td>{result.header[idx].toString()}</td>                
            <td>{result.body[idx].toString()}</td>                
        </tr>
      ))

Upvotes: -3

Related Questions