You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Angular 13将指定JSON数组数据展示为表格?

表格展示功能实现与代码优化

原始JSON数据

[
  {
    "group": "A",
    "teams": [
      {
        "id": 1,
        "name": "France"
      },
      {
        "id": 2,
        "name": "Portugual"
      }
    ]
  },
  {
    "group": "B",
    "teams": [
      {
        "id": 3,
        "name": "France"
      },
      {
        "id": 4,
        "name": "Portugual"
      }
    ]
  },
  {
    "group": "C",
    "teams": [
      {
        "id": 5,
        "name": "France"
      },
      {
        "id": 6,
        "name": "Portugual"
      }
    ]
  }
]

需求说明

需将上述数据转换为表格:首列显示球队名称,后续列对应分组A、B、C,单元格展示该球队在对应分组的ID,无匹配数据则显示NA。

原尝试代码

TypeScript代码

this.props = this.input.map((x: any) => x.group);
this.output = this.input.reduce(
  (acc: { name: string; [key: string]: any }[], cur: any) => {
    for (let team of cur.teams) {
      let obj: { name: string; [key: string]: any } = { name: team.name };
      for (let prop of this.props) {
        obj[prop] = prop === cur.group ? team.id : undefined;
      }
      acc.push(obj);
    }
    return acc;
  },
  [] as { name: string; [key: string]: any }[]
);

HTML代码

<table>
  <thead>
    <tr>
      <th>Name</th>
      <ng-container ngFor="let prop of props">
        <th>{{prop}}</th>
      </ng-container>
    </tr>
  </thead>
  <tbody>
    <tr ngFor="let row of output">
      <td>{{row.name}}</td>
      <ng-container *ngFor="let prop of props">
        <th>{{row[prop]??'NA'}}</th>
      </ng-container>
    </tr>
  </tbody>
</table>

优化实现方案

原代码会生成重复的球队行(同一球队对应每个分组各一行),不符合表格需求。以下是修正后的代码:

优化后的TypeScript代码

// 提取所有分组
this.props = this.input.map(item => item.group);

// 收集所有唯一的球队名称
const allTeamNames = [...new Set(this.input.flatMap(item => item.teams.map(team => team.name)))];

// 构造输出数据:每个球队一行,匹配所有分组的ID
this.output = allTeamNames.map(name => {
  const row: { name: string; [key: string]: number | 'NA' } = { name };
  this.props.forEach(group => {
    const team = this.input.find(item => item.group === group)?.teams.find(t => t.name === name);
    row[group] = team ? team.id : 'NA';
  });
  return row;
});

修正后的HTML代码

<table>
  <thead>
    <tr>
      <th>Name</th>
      <ng-container *ngFor="let prop of props">
        <th>{{prop}}</th>
      </ng-container>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let row of output">
      <td>{{row.name}}</td>
      <ng-container *ngFor="let prop of props">
        <td>{{row[prop]}}</td>
      </ng-container>
    </tr>
  </tbody>
</table>

优化点说明

  1. 去重球队行:通过Set收集唯一球队名称,确保每个球队仅显示一行
  2. 高效匹配ID:遍历每个球队时,匹配所有分组对应的ID,避免冗余数据
  3. 修正HTML标签错误:将tbody中的<th>改为<td>,符合表格语义规范
  4. 默认值处理:直接在数据构造阶段设置NA,简化模板逻辑

内容的提问来源于stack exchange,提问作者Er. IT

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 04:20:16