Search code examples
jsonreactjsreact-hooksfetchpapaparse

Get all JSON headers from different files


I'm making a program in React using Hooks that need to read a CSV file and convert it into a JSON, then I want to create a table from the file but the file may change as also the variables and the headers (column name) of each attribute.

How can I get the headers depending on the file so then I can create the table automatically depending on the file and not on the code?

For the CSV to JSON I use react-papaparse, and I'm trying to create a basic table to preview the data using React.

CSVReader

<CSVReader
        onDrop={handleOnDrop}
        onError={handleOnError}
        addRemoveButton
        onRemoveFile={handleOnRemoveFile}
        config={{ header: true }}
      >
        <span>Drop CSV file here or click to upload.</span>
</CSVReader>

Then I assign the data to the state using Hooks

  const handleOnDrop = (data) => {
    console.log("---------------");
    console.log(data);
    setFileData(data);
    console.log("---------------");
  };

The problem is that the only way to see each data is in code:

<div>
        {fileData.map((data, index) => (
          <li key={index}>{data.data.ASEG_LeftLateralVentricle}</li>
        ))}
</div>

In some files, the ASEG_LeftLateralVentricle has not that name but I also want to show the information of columns 1, 2, ...

Everything should be done on the front end.


Solution

  • The way I get all the headers of the JSON file was using the following:

    const getKeys = (data) => {
        let arr = [];
        if (data) {
          Object.keys(data).map((key) => {
            arr = Object.keys(data[key].data);
          });
        }
        return arr;
      };