简体   繁体   English

将 json 数组转换为 object - Javascript

[英]Convert json array to object - Javascript

What I'm trying to do is show the data I get from an API (did using NodeJs) and display it in a table using the material-table library using React Js.我想要做的是显示我从 API(使用 NodeJs)获得的数据,并使用 React Js 使用材料表库将其显示在表中。 My problem is when making the data I get from the API compatible with the json format that the table understands.我的问题是当我从 API 获得的数据与表格理解的 json 格式兼容时。 I think the problem is because the format the table understands is in an array, but I still don't understand how to do that.我认为问题在于表格理解的格式是数组,但我仍然不明白如何做到这一点。

In this JSON format it does not display any data in the table:在此 JSON 格式中,它不会在表中显示任何数据:

{
  "data": {
    "username01": {
      "name": "john",
      "adress": "street sun, 124",
      "status": "ok"
    },
    "username02": {
      "name": "joseph",
      "adress": "street abc, 124",
      "status": "ok"
    }
  }
}

The JSON format that I tested and displays in the table normally:我测试的JSON格式在表格中正常显示:

{
  "data": [
    {
      "name": "john",
       "adress": "street sun, 124",
       "status": "ok"
    },
    {
       "name": "john",
       "adress": "street sun, 124",
       "status": "ok"
    }
  ]
}

ReactJs Frontend: ReactJs 前端:

const columns = [
  { title: 'Name', field: 'name' },
  { title: 'Adress', field: 'adress' },
  { title: 'Status', field: 'status' }
];


const getdata = async () => {
await api.post("/data")
  .then(response => {
    setData(response.data.data);
  }).catch(error => {
    console.log(error);
  })
 }


<MaterialTable
     columns={columns}
     data={data}
     title="Lista de entregadores"
            
     options={{
         actionsColumnIndex: -1,
         exportButton: true
     }}
 />

Try this:尝试这个:

 setData(Object.values(response.data.data));

or in component:或在组件中:

 <MaterialTable
     columns={columns}
     data={Object.values(data)}
     title="Lista de entregadores"
            
     options={{
         actionsColumnIndex: -1,
         exportButton: true
     }}
 />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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