Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Making a table in react js without proper key values in json data

I am getting data from an API and it does not have proper key values and headers to use react-table. I am not sure how to generate table with the data

{
  "result": {
    "DB04571": {
      "CC1=CC2": -4.204354763031006
    },
    "DB00855": {
      "NCC(=O)": -3.666783332824707
    },
    "DB09536": {
      "O=[Ti]": -3.1173958778381348
    }
}}

The above is a sample of the data of 1000 entries. Below is the picture how i was expecting the table should be. as i am not having the headers for the json output i was unable to store them as a table as the value keeps on changing. while using react-table i should have to mention the headers but i cannot pull the data as the drug name keeps on changing in the data and their is no key attached to it.

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

To render with react-table you need to convert your object in array of objects:

const normalizeData = (data) =>
    Object.keys(data).map((key) => ({
      drug: key,
      molecule: Object.keys(data[key]),
      prediction: Object.values(data[key])
    }));

Normalize function return an array of object can be render with react-table:

[{"drug":"DB04571","molecule":["CC1=CC2"],"prediction":[-4.204354763031006]}, ...] 

The react component:


const MyPage = () => {
  const columns = [{ accessor: "drug" }, { accessor: "molecule" },{ accessor: "prediction" }];

  const data = {
    result: {
      DB04571: {
        "CC1=CC2": -4.204354763031006
      },
      DB00855: {
        "NCC(=O)": -3.666783332824707
      },
      DB09536: {
        "O=[Ti]": -3.1173958778381348
      }
    }
  };

  const normalizeData = (data) =>
    Object.keys(data).map((key) => ({
      drug: key,
      molecule: Object.keys(data[key]),
      prediction: Object.values(data[key])
    }));

return <Table columns={columns} data={normalizeData(data.result)} />
}

Here a live example:

Edit young-dust-pguhw

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading