kintela
kintela

Reputation: 1333

how to setRowdata with complex objects

I have this columndefs enter image description here

But the source of data is this array. enter image description here

So I only see projectId and projectName in the grid. enter image description here

Is it possible assign this array or I might change his structure? Thanks

Upvotes: 1

Views: 400

Answers (1)

nakhodkin
nakhodkin

Reputation: 1465

In order to be able to set the data through the setRowData method of ag-Grid API, you have to make sure, that either of data entry is consistent between any other.

You can try to consider the following ways to solve this.

  1. Data transformation on back-end side
    It might be the case if you are full of control over the back-end API, just send right back to the client the data in the most appropriate way for you.

  2. Splitting the process of setting data from setRowData
    You may want to introduce some additional methods for your component with data-grid e.g. one for setting projectId and projectName and another for setting calendarValues. ag-Grid docs offers up to 4 different ways of updating the data.

  3. Defining custom valueGetter for each column
    You can try to modify definitions for columnDefs by introducing custom valueGetter which would take care of extracting appropriate value e.g.

  const columnDefs = [
    {
      headerName: "Febrero2019",
      field: "Febrero2019",
      valueGetter({ data: { calendarValues } }) {
        return calendarValues['Febrero2019'];
      }
    },
  ];
  1. Preprocessing data that comes from the API
    In your case, you can define a tiny little helper function that would handle the process of transforming raw data from the API into an appropriate format of data acceptable for api.setRowData method.
const colDefs = [
    { headerName: 'Codigo', field: 'projectId' },
    { headerName: 'Nombre', field: 'projectName' },
    { headerName: 'Febrero2019', field: 'Febrero2019' },
    { headerName: 'Marzo2019', field: 'Marzo2019' }
];

const projectData = {
    calendarValues: [
        { date: 'Febrero2019', value: 0 },
        { date: 'Marzo2019', value: 0 },
    ],
    projectId: 'SomeId',
    projectName: 'SomeName'
};

const processData = ({ projectId, projectName, calendarValues }) => ({
    projectId,
    projectName,
    ...calendarValues.reduce((calendar, { date, value }) => ({ ...calendar, [date]: value }), {})
});

so the call processData will result in the desired data format.

{
  Febrero2019: 0
  Marzo2019: 0
  projectId: "SomeId"
  projectName: "SomeName"
}

Upvotes: 1

Related Questions