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.
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
Most helpful comment
I think the only way you have is to flatten your data structure.