Mui-datatables: How to access nested object properties in columns

Created on 2 Apr 2019  路  5Comments  路  Source: gregnb/mui-datatables

Hello, I am passing an array of objects in data prop. Those objects in the array have some nested objects. I need to access the nested object properties. How can I do that?
Demo data:

const data = [
{
    id: 1,
    person: {
      name: "Bla"
    }
  },
  {
    id: 2,
    person: {
      name: "Lol"
    }
  }
]

Expected column:

<MUIDataTable
title="Person List"
columns={
  [{
      name: 'id',
      label: 'ID',
      options: {
        filter: true,
        sort: true,
      }
    },
    {
      name: 'person.name',
      label:  'Person Name',
      options: {
        filter: true,
        sort: false,
      },
    },
  ]
}
data={history}
/>

So all I want is to show the person name in column. How can I do that? The person.name in above code doesn't work.

Most helpful comment

I think the only way you have is to flatten your data structure.

All 5 comments

I think the only way you have is to flatten your data structure.

https://jsbin.com/kinufuseki/edit?js,console

This way I use it.

@wdh2100 Hey! Thanks for your reply. I was able to flatten my object using your code. But problem is, in my real data there are many unused properties, which I don't want to show in columns. I want to show specific items in columns. How can I do that?

Hey thanks for all the response. My problem is solved.

function flattenObject(ob) {
  const toReturn = {};

  Object.keys(ob).map(i => {
    if (typeof ob[i] === 'object' && ob[i] !== null) {
      const flatObject = flattenObject(ob[i]);
      Object.keys(flatObject).map(x => {
        toReturn[`${i}.${x}`] = flatObject[x];
        return x;
      });
    } else {
      toReturn[i] = ob[i];
    }
    return i;
  });
  return toReturn;
}

I got data like:

{
  id: 2,
  "person.name": "Lol"
}

i didnot like that how to use sub object without flatten

Was this page helpful?
0 / 5 - 0 ratings

Related issues

kylane picture kylane  路  3Comments

Aankhen picture Aankhen  路  3Comments

harryluo91 picture harryluo91  路  3Comments

ronaiza-cardoso picture ronaiza-cardoso  路  3Comments

cahna picture cahna  路  3Comments