如何从 MUI 数据表格中的对象中获取子对象的值

huangapple go评论60阅读模式
英文:

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 the 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']".

英文:

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']".

答案1

得分: 2

你不能使用field属性访问嵌套对象,但可以使用value getter

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

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
  }
];

huangapple
  • 本文由 发表于 2023年3月7日 17:53:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/75660385.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定