将数据作为键值对,在网格上具有列及其计算值



我使用了ag网格,有些列使用直接值,有些列则使用valueGetters。

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

实际的行数据对我来说是可用的,因为我已经为ag网格提供了行数据。问题是,我找不到任何方法来获得以下格式的数据:

以列为键,从ag网格的valueGetters获得的渲染值为值的键值对

例如:[{column1:"column1Data",column2:"column2Data",column3:"column3Data_found_using_valueGetter"}]

否则,我必须处理实际的行数据才能获得上述格式。

终于找到了这个问题的解决方案。

在我的研究中,没有特定的方法来检索ag网格上显示的细节。但是我们可以使用getDataAsCsv((方法,它将以csv格式返回ag网格的标题和行值,我们可以将数据格式化为所需的格式。

CSV数据:

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

以下是获取ag网格上显示的数据键值对的代码:

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);
}

结果:

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

最新更新