javascriptreactjsmaterial-uimui-x-data-grid

How can I get child object value from object in MUI Datagrid


I am using this method:

useEffect(() => {
    PetService.getAll("/pets")
      .then(response => {
        setData(response.content);
      })
  }, [setData]);

and get this response:

{
    "timestamp": 1678181099411,
    "message": "Success",
    "data": {
        "content": [
            {
                "id": 1,
                "name": "Tom",
                "type": {
                    "id": 3,
                    "name": "Cat"
                },
...

However, although I can get the content values properly, I cannot get name of the type value on MUI Datagrid. I use this config for columns:

export const petColumns = [
  { 
    field: "id", 

  },
  {
    field: "name",
    headerName: "Pet Name"

  {
    field: "type.name",
    headerName: "Type"
  }
];

So, how can I access the value of the child object? I also tried "type['name']".


Solution

  • You can't access nested objects with the field property, but can use a value getter:

    export const petColumns = [
      { 
        field: "id", 
    
      },
      {
        field: "name",
        headerName: "Pet Name"
    
      {
        field: "type.name",
        headerName: "Type",
        valueGetter: ({ row }) => row.type.name
      }
    ];