Search code examples
angularag-gridag-grid-angular

Getting data as key value pairs having columns and its calculated values on ag-gird


I've used ag-grid with some columns using direct values and some columns using valueGetters.

  columnDef: ColDef[] = [
    { field: 'column1' },
    { field: 'column2' },
    { headerName: 'column3', valueGetter: this.getColumn3Value }
  ];

The actual row data will be available to me, since I've provided the ag-grid with row data. The problem is that I could not find any way to get the data in the below format:

Key value pair having columns as key and rendered value obtained from valueGetters of ag-grid as value.

eg: [{column1:'column1Data', column2: 'column2Data', column3: 'column3Data_found_using_valueGetter'}]

Otherwise I have to process the actual row data to get the above format.


Solution

  • Finally I've got a solution for this problem.

    In my research, there is no particular method to retrieve the details displayed on ag-grid. But we can use getDataAsCsv() method, which will return the headers and row values of ag-grid in csv format, we can format the data into desired format.

    CSV data:

    "Athlete","Country","Sport","Total"
    "Eamon Sullivan","Australia","Swimming","3"
    "Dara Torres","United States","Swimming","3"
    

    Here is the code to get key value pairs of data displayed on ag-grid:

    onGridReady(event){
       this.gridApi = event.api;
    }
    
    csvToKeyvaluePair() {
        // Removes the doube quotes present on each string
        let csvData = this.gridApi.getDataAsCsv().replace(/"/g, "");
    
        // Splits header and each row values
        let [header, ...values] = csvData.split('\n');
    
        // Returns an array of header value 
        let headerLine = header.split(',');
    
        // Generate an array of key value pairs
        let displayedData = values.map((item, index) => {
          return item.split(',').reduce((result, current, index) => ({ ...index === 1 ? { [headerLine[0]]: result } : result, ...index === 1 ? { [headerLine[1]]: current } : { [headerLine[index]]: current } }));
        });
    
        //  Displays row data in key value pairs
        console.log(displayedData);
    }
    

    Result:

    [
      {
        Athlete: "Eamon Sullivan",
        Country: "Australia",
        Sport: "Swimming",
        Total: "3"
      },
      {
        Athlete: "Dara Torres",
        Country: "United States",
        Sport: "Swimming",
        Total: "3"
      }
    ]