Return everything instead of just the first key item using .map in React JSX

const table_body = [
  {
    id: "1",
    first_name: "Test",
    last_name: "Again",
    email: "[email protected]",
  },
  {
    id: "2",
    first_name: "Joe",
    last_name: "Bidal",
    email: "[email protected]",
  }
]          

This is my array of objects.

<tbody className="lh-copy">
    <tr className="stripe-dark">
      {Object.values(this.props.table_body).map((item, i) => {
      for (const item of Object.values(item)) {
        return (
            console.log(item)
            // <td key={i} className="pa3">{item}</td>

        }
      })}
    </tr>
</tbody>

I have a table component and I am returning the values for the table dynamically based on the array of object. I want to make a dynamic table with dynamic data.

I don't want to use multiple <td> tag because I want users to be able to add more inputs and the object's content will not just be id, first_name, last_name, and email, it could be more so {item.id}....... will not work for my case.

When I read the returned console.log it shows 1 and 2 only which is the id number. If I remove the return(), it will display the id, first_name, last_name, email.

The question is how do I return everything either at the console.log to test or in the td tag? I tried using a for loop in the return() but it doesn't work apparently.

UPDATE: This is my working code portion, thanks to @kind_user

    {table_body.map((item, i) => {
      return (
        <tr key={i} className="stripe-dark">
          {Object.keys(item).map((element, j) => {
            return(
              <td key={j} className="pa3">{element}</td>
            )
          })}
        </tr>
      )
    })}
728x90

2 Answers Return everything instead of just the first key item using .map in React JSX

  • return keyword breaks the loop after first cycle, that's why you are getting only the first element.

  • table_body is an array. Object.values function is redundant.

  • You have placed <tr /> in a wrong place.

Suggested approach:

{table_body.map((item, i) => (
   <tr className="stripe-dark" key={i}>
      {Object.values(item).map((elem) => <td className="pa3">{elem}</td>)}
   </tr>
)}

2 weeks ago

Mapping through the array will give you every object separately.

  <tbody className="lh-copy">
    {table_body.map((item, index) => (
      <tr className="stripe-dark" key={index}>
        <td className="pa3">{item.id}</td>
        <td className="pa3">{item.email}</td>
      </tr>
    ))}
  </tbody>

A sandbox: https://codesandbox.io/s/kor9lwvn87

2 weeks ago