如何在AG-Grid中按数组内的值分组?现有方案无法实现
AG-Grid按数组内值分组的实现方法
要实现按数组内的每个值分组,核心是让每行数据与数组中的每个标签建立独立的分组关联。AG-Grid默认不支持直接按数组分组,可通过以下两种方案解决:
方案一:数据扁平化预处理
将包含数组的行数据拆分为多条,每条对应数组中的一个元素,直接利用AG-Grid原生分组能力:
import { AgGridReact } from '@ag-grid-community/react'; import { ClientSideRowModelModule, RowGroupingModule } from '@ag-grid-community/all-modules'; const Example = () => { // 原始数据 const rawRowData = [ {name: "row1", tags: ["tag1", "tag2"]}, {name: "row2", tags: ["tag2", "tag3"]} ]; // 扁平化数据:每个标签对应一条数据 const rowData = rawRowData.flatMap(row => row.tags.map(tag => ({ ...row, tag })) ); const columnDefs = [ {headerName: "Name", field: "name"}, {headerName: "Tag", field: "tag", rowGroup: true, hide: true}, {headerName: "Tags", field: "tags"} ]; return ( <AgGridReact rowData={rowData} columnDefs={columnDefs} rowGroupPanelShow={'always'} modules={[ClientSideRowModelModule, RowGroupingModule]} autoGroupColumnDef={{headerName: "Tags Group", field: "tag"}} /> ); };
此方案简单直接,适合数据量不大的场景,无需复杂配置。
方案二:自定义分组逻辑(保留原始数据)
若不想修改原始数据,可通过AG-Grid的自定义API实现分组逻辑(需Enterprise版本支持):
import { AgGridReact } from '@ag-grid-community/react'; import { ClientSideRowModelModule, RowGroupingModule } from '@ag-grid-community/all-modules'; const Example = () => { const rowData = [ {name: "row1", tags: ["tag1", "tag2"]}, {name: "row2", tags: ["tag2", "tag3"]} ]; const columnDefs = [ {headerName: "Name", field: "name"}, {headerName: "Tags", field: "tags", rowGroup: true, hide: true} ]; // 返回当前行的所有标签作为分组键 const getRowGroupKey = params => { return params.rowNode.data.tags; }; // 聚合分组节点,将同一标签的行归为一组 const groupRowAggNodes = params => { const tagMap = new Map(); params.nodes.forEach(node => { node.data.tags.forEach(tag => { if (!tagMap.has(tag)) { tagMap.set(tag, []); } tagMap.get(tag).push(node); }); }); // 转换为AG-Grid需要的分组节点结构 return Array.from(tagMap.entries()).map(([tag, nodes]) => ({ key: tag, rowNodes: nodes, aggData: { tags: tag } })); }; return ( <AgGridReact rowData={rowData} columnDefs={columnDefs} rowGroupPanelShow={'always'} modules={[ClientSideRowModelModule, RowGroupingModule]} getRowGroupKey={getRowGroupKey} groupRowAggNodes={groupRowAggNodes} autoGroupColumnDef={{headerName: "Tags Group", valueGetter: params => params.data.tags}} /> ); };
此方案保留原始数据结构,适合需要维持数据完整性的场景。
注意事项
- 方案一中,扁平化后会出现重复行记录,可通过单元格渲染器或列配置隐藏重复内容。
- 方案二中的
groupRowAggNodes是Enterprise版本API,社区版建议优先使用方案一。
内容的提问来源于stack exchange,提问作者dvreed77
相关产品推荐
相关产品推荐

