Skip to content
Advertisement

how to set column name in mui datatables using object key

I’m trying to use an object key to set the name of a column in MUI Datatables. I’m trying to set one of the column names with the first element of children.childName so that in that column it will display list of child names, but only the first child.

In Current way that Im trying this, I am getting no errors, and its displaying nothing in the childName Column on the table.

How Can I access an object thats inside an array?

screen shot of display table

This is my Data:

    const data = [
  {
    name: "Pat",
    company: "Test Corp",
    city: "Yonkers",
    state: "NY",
    children: [
      { childName: "Pat Jun", childAge: 2 },
      { childName: "Mary Jun", childAge: 2 }
    ]
  },
];


    const columns = [
  {
    name:name: data[0]["children"][0]["childName"],
    label: "Child Name",
    options: {
      filter: true,
      sort: true
    }
  }]

MuiTable.js

function MuiTable({ forms }) {
  console.log("cols", columns);
  return (
    <MUIDataTable
      title={"Title"}
      data={data}
      columns={columns}
      options={options}
    />
  );
}

By doing a console.log I can see that it is printing the value instead of the object key name

console.log of columns

I would really appreciate any help, Thank you.

Advertisement

Answer

Thanks very much to @Klaus your answer. That’s pretty much what I had to do, but In my case, I wanted to only display the first childName in the object children which was in an array of objects. So I had to adapt it a bit and change my data structure as well.

This is what I ended up doing. I first added a simple array to my data structure completely seperate to the array containing the children objects called childNames, which just came contained only the names.

new data structure containing childNames array

This made it alot easier to access the childNames as it was just a simple array not nested in anything. So I simply just displayed the first element in the array on Table

const columns = [
{
  name: "childNames",
  label: "Child Name",
  options: {
    filter: true,
    customBodyRender: (value, tableMeta, updateValue) => {
      return <div>{value[0]}</div>;
    }
  }
},

The reason why I created an array for just childNames, was because trying to access only just the first childName in the array containing children objects was proving very complicated and difficult.

Thanks very much for all the help.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement