我需要将嵌套的 JSON 数据解析为来自 API 的普通 JSON,并且需要将该 JSON 数据传递到反应数据网格(使用材料 ui 中可用的数据网格),如下所示:
json数据
{
"rows": [
{
"id": 101,
"name": "sample",
"last_modified": "sample time",
"countries": [
{
"country_id": 1,
"country_name": "countryA"
},
{
"country_id": 2,
"country_name": "countryB"
}
]
},
{
"id": 102,
"name": "sample 2",
"last_modified": "sample time",
"cdn": [
{
"country_id": 3,
"country_name": "countryC"
},
{
"country_id": 4,
"country_name": "countryD"
}
]
}
]
}
在数据.JSX
const checkKeysUnderObject = (obj, result) => {
for (let key in obj) {
if (key) {
result.push(key + " : " + obj[key]);
}
}
};
const columns = [
{ field: 'id', headerName: 'ID', width: 100, hide: true, disableColumnFilter: true, disableColumnSelector: true, headerAlign:'center'},
{
field: 'id',
headerName: 'ID',
width: 250,
editable: false,
},
{
field: 'name',
headerName: 'Name',
width: 250,
editable: false,
},
{
field: 'last_modified',
headerName: 'Last Modified',
width: 250,
editable: false,
},
{
field: 'countries',
headerName: 'Countries',
width: 500,
editable: false,
disableColumnFilter: true,
valueGetter: (params) => {
console.log({ params });
let result = [];
if (params.row.countries) {
checkKeysUnderObject(params.row.countries, result);
} else {
result = ["Unknown"];
}:
return result.join(" , ");
}
},
}
];
获取打印 country_id 和 country_name 所需的以下输出
0 : [object Object] , 1 : [object Object]
在控制台日志中
params
params
id: 101, field: countries, row:
countries: Array(2)
0: {country_id: 1, country_name: 'countryA'}
1: {country_id: 2, country_name: 'countryB'}
length: 2
[[Prototype]]: Array(0)
id: 101
last_modified: "sample time"
name: "sample"
[[Prototype]]: Object
使用 DataGrid 显示
<DataGrid
rows={response}
columns={columns}
//pageSize={5}
//rowsPerPageOptions={[5]}
autoPageSize
density='standard'
/>
任何人都可以帮忙。
问题:How to render nested JSON elements in ReactJS material-ui based DataGrid? Please provide solution to this issue.