0

I have a slightly strange problem that i cant solve. I have to render a table using react - however my data structure is such that i need the name from the first level to be the table headings - I then need to map the data associated to that heading into the correct cells in the table.

Here is my data

[{
    "cell_id": 1,
    "step_data": [{
      "width": 1920,
      "name": "bruce",
    }, {
      "width": 2236,
      "name": "ben",

      }],
        "cell_name": " boys names"
      },
{
        "cell_id": 2,
        "step_data": [{
          "width": 1920,
          "name": "grace",
        }, {
          "width": 2236,
          "name": "megan",

        }],
        "cell_name": "girls names"
      }

To map the table headings i do this which dynamically renders the headings however I cant seem to put the data under the correct headings as they all go on the same row.

Any ideas how i do this?

My desired task is to have a table with two headings boys names and girls names - I need the step_data from boys names to be rows under the boys name heading and the step data from girls names to be under the girls names heading

<table className="table">
    <tbody>
      <tr>
        {this.props.data.map((item, key) => <th key={key}>{item.cell_name}</th>
        )}

      </tr>
      {this.props.data.map(data => data.map((z, key) => <td key={key}>{z.name}</td>))}

      <tr>

      </tr>

    </tbody>
  </table>

1 Answer 1

1
{[
  ...Array( // get the number of rows you need to create
    Math.max(...this.props.data.map(({ step_data }) => step_data.length))
  ).keys()
].map(i => (
  <tr key={i}>
    {this.props.data.map(({ step_data, cell_name }) => (
      <td key={cell_name}>{(step_data[i] || {}).name}</td>
    ))}
  </tr>
))}
Sign up to request clarification or add additional context in comments.

2 Comments

Could you please explain the syntax <td key={cell_name}>{(step_data[i] || {}).name}</td> Not sure I fully understand what is going on?
It creates a td with the value step_data[i].name, and prevents crash if step_data[i] is undefined (this happens if one array is longer than the other).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.