0

I have configured a react website to receive json data and store it into an array in the format depicted in the attached image. How would I go about displaying this information in a table format?json data stored in array

1 Answers1

1

If you don't want to use property names, you could do something like that :

import React, { Component } from "react";
import { render } from "react-dom";

const App = () => {
  const data = [
    { id: 0, value: "item 1" },
    { id: 1, value: "item 2" },
    { id: 2, value: "item 3" }
  ];
  const keys = Object.keys(data[0]);

  return (
    <div>
      <table>
        <thead>
          {keys.map(key => {
            return (
              <th>
                <td>{key}</td>
              </th>
            );
          })}
        </thead>
        <tbody>
          {data.map((item, index) => {
            return (
              <tr>
                {keys.map(key => (
                  <td>{item[key]}</td>
                ))}
              </tr>
            );
          })}
        </tbody>
      </table>
    </div>
  );
};

render(<App />, document.getElementById("root"));

Note that all of your items need to have the same properties (here 'id' and 'value') for this to work.

Here is the repro on stackblitz

If you need something better then you should look for a package made for this, there's plenty on internet.

Quentin Grisel
  • 4,794
  • 1
  • 10
  • 15