Home > front end >  Making a table in react js without proper key values in json data
Making a table in react js without proper key values in json data

Time:02-16

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

CodePudding user response:

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

CodePudding user response:

With explicit variable names:

Object.keys(data.result).map(( drug ) => {
    const drugData = data.result[ drug ];
    const molecule = Object.keys(drugData)[ 0 ];
    const prediction = drugData[ molecule ];
    /* More code */
});
  • Related