Material UI datagrid with nested data
To solve the problem, let's see params
object passed in valueGetter
function. Log that and you will find a row
object under it. Instead of using params.getValue()
, you should access the row
object. It seems that params.getValue()
can only be used on one-level JSON object. Here is the code snippet to output phone
field.
{ field: "phone", headerName: "Phone", width: 160, valueGetter: (params) => { console.log({ params }); let result = []; if (params.row.phone) { if (params.row.phone.home) { result.push("home: " + params.row.phone.home); } if (params.row.phone.office) { result.push("office: " + params.row.phone.office); } } else { result = ["Unknown"]; } return result.join(", "); } }
Update
To have more flexibility on checking if every key under a object exists, I have created a helper method:
const checkKeysUnderObject = (obj, result) => { for (let key in obj) { if (key) { // push the value to the result array only if key exists result.push(key + ": " + obj[key]); } }};
usage of the helper method:
if (params.row.phone) { checkKeysUnderObject(params.row.phone, result);}else{ result = ["Unknown"];}
I have also updated the codesandbox here.
I use this in my project :
{ field: 'idMaintenancePlan', headerName: 'Plan de maintenance', sortable: false, width: 200, valueFormatter: (params) => params.row?.maintenancePlan?.name }
this works fine for me
{ field: 'parserInfo', headerName: 'Parser Title', valueFormatter: ({ value }) => value.title }