Angular中如何将按index分组的嵌套对象数组格式化为多个HTML表格
解决方案
第一步:调整数据处理逻辑,按index分组
你只需要在现有数据处理的基础上,把扁平的结果数组按index字段做分组聚合即可,同index下的所有value会被归集到同一组,同时自动提取该组对应的表格列名:
let results: any[][] = await this.searchAllIndexes(searchTerm); const result = []; results.forEach(i => i.forEach(j => { let json = { index: j._index, value: j._source //j._source is an object itself } result.push(json) //result是函数内部的局部对象数组 })) // 新增分组逻辑 this.groupedIndexData = result.reduce((acc, curr) => { // 如果当前index还没在分组中,初始化分组结构 if (!acc[curr.index]) { acc[curr.index] = { columns: Object.keys(curr.value), // 提取该index对应的表格列名 rows: [] // 存储该index下的所有行数据 } } // 把当前value加入对应分组的行数据中 acc[curr.index].rows.push(curr.value); return acc; }, {});
处理后groupedIndexData的结构为:
{ "index_1": { "columns": ["property-1", "property-2", "property-3"], "rows": [ {"property-1": "value-1", "property-2": "value-2", "property-3": "value-3"}, {"property-1": "value-1", "property-2": "value-2", "property-3": "value-3"} ] }, "index_2": { "columns": ["property-1", "property-2", "property-3", "property-4"], "rows": [ {"property-1": "value-1", "property-2": "value-2", "property-3": "value-3", "property-4": "value-4"} ] } }
第二步:编写模板渲染逻辑
直接遍历分组后的数据即可实现每个index对应单独表格的需求,示例模板代码如下:
<!-- 遍历所有index分组 --> <div *ngFor="let indexGroup of groupedIndexData | keyvalue"> <h2>当前索引:{{ indexGroup.key }}</h2> <table style="border-collapse: collapse; width: 100%; margin: 16px 0;"> <thead> <tr style="background: #f5f5f5;"> <!-- 渲染当前分组的列名 --> <th *ngFor="let col of indexGroup.value.columns" style="border: 1px solid #ddd; padding: 8px;"> {{ col }} </th> </tr> </thead> <tbody> <!-- 渲染当前分组的每一行数据 --> <tr *ngFor="let row of indexGroup.value.rows"> <td *ngFor="let col of indexGroup.value.columns" style="border: 1px solid #ddd; padding: 8px;"> {{ row[col] }} </td> </tr> </tbody> </table> </div>
可选优化点
- 如果使用Angular 17及以上版本,可以用
@for语法替代*ngFor获得更好的性能 - 如果需要保留index出现的原始顺序,可给
keyvalue管道传入自定义比较函数(a,b) => 0即可不做排序 - 可给
*ngFor添加trackBy函数减少不必要的DOM重渲染
内容的提问来源于stack exchange,提问作者proverbialTurdNugget
相关产品推荐
相关产品推荐

