Given the following example from MUI data grid docs v7.10.0:
const tempColumns: GridColDef[] = [
{ field: "id", headerName: "ID", width: 90 },
{
field: "firstName",
headerName: "First name",
width: 150,
},
{
field: "lastName",
headerName: "Last name",
width: 150,
},
];
const rows = [
{ id: 1, lastName: 'Snow', firstName: 'Jon' },
{ id: 2, lastName: 'Lannister', firstName: 'Cersei' },
{ id: 3, lastName: 'Lannister', firstName: 'Jaime' },
];
In the example above, the rows is initialized with hardcoded values and fields.
The Columns will be generated dynamically (user customizable). Imagine the data for definition of columns comes from an API endpoint. The data for the rows, comes from another (1 or more) API endpoints.
How can the rows array be initialized by fetching some data from an API, and then stitching together an array of objects which can be fed into the rows property of the DataGrid component?
I am guessing that there is a way to examine the Columns array and fetch the name of the fields used, but how?
I can not just do the following (because I do not know about the existence of "field" and "field2", and even if I did, there could be a 100 fields and we don't really want to go down that path):
rows.push({
id: 1,
field: "some value",
field2: "some value"
})
Is there a generic way of doing this?
I do not completely understand what you are asking however here is how I would fetch the keys of an array of objects that don't have a standard type.
Assuming the columns you received do not have the same keys, you can do something like this:
const columns = [{
field: 'id',
headerName: 'ID',
width: 90
},
{
field5: 'firstName',
header: 'First name',
length: 150
},
];
let dataKeys: any = [];
columns.forEach(col => dataKeys.push(Object.keys(col)))
console.log(dataKeys)
On the other hand if they all have the same keys it is much easier to just use
const dataKeys = Object.keys(column[0])
If this is not what you were asking for let me know and I will try my best to answer your question.