0

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>
4
  • 2
    You need to loop over result.header and result.body as well Commented May 22, 2019 at 14:55
  • how long will the list array be ? it's really unpractical to do it this way. Commented May 22, 2019 at 14:56
  • @k.s. it's an array with 2 objects Commented May 22, 2019 at 14:59
  • @mr.abdo will it always be just an array with two objects ? Commented May 22, 2019 at 15:00

2 Answers 2

4

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>)
Sign up to request clarification or add additional context in comments.

7 Comments

Tks for your help. I got this error Uncaught TypeError: Cannot read property 'map' of undefined but I'm trying to solve it.
maybe the list variable is not defined on the initial load
or there will be an element not containing header property
It was my mistake. I fix it and I got this error Uncaught TypeError: Cannot read property '0' of undefined
I've updated your fiddle at jsfiddle.net/2x3f5hqr and also updated my answer
|
-3

try:

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

3 Comments

I got this error Uncaught TypeError: Cannot read property '0' of undefined
why are you using toString() here?
just to be sure integers, array and whatnot are converted to string

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.