How to map nested JSON data in ReactJS and display in a simple table

Viewed 17

I have this data:

[
  {
    "s": "s1",
    "p": "p1",
    "x": ["d11", "d12", "d11439"],
    "y": ["t11", "t12", "t11439"]
  },
  {
    "s": "s2",
    "p": "p1",
    "x": ["d11", "d12", "d11439"],
    "y": ["t21", "t22", "t21439"]
  }
]

I need to display it in a simple scrollable table in this format:

Index    |     s1     |     s2
--------------------------------
d11      |    t11     |    t21
d12      |    t12     |    t22
...      |    ...     |    ...
d11439   |  t11439    |  t21439

How do I do this using the map function in ReactJS?

I have this unitial code but its not working as expected:

const header = data.map((k, v) => {
  return <th key={v}>{k.s}</th>;
});
const index = data[0].x;
console.log("index", index);

return (
  <div className="App">
    <h1>Hello CodeSandbox</h1>
    <h2>Start editing to see some magic happen!</h2>

    <Table responsive="md" striped bordered hover variant="light">
      <thead>
        <tr>
          <th>Index</th>
          {header}
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>
            {index.map(d=>(
              <tr>{d}</tr>
            ))}
          </td>
        </tr>
      </tbody>
    </Table>
  </div>
);

as it shows something like this this

instead of this should-be

0 Answers
Related