简体   繁体   中英

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.

在此处输入图像描述

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:

编辑 young-dust-pguhw

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 */
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM