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

Angular中对比数组并在表格展示匹配值的问题排查

问题分析与解决方案

问题根源

  1. 变量覆盖问题:你定义的matchedValues是单个变量,每次匹配到对应ID时都会用新值覆盖旧值,循环结束后它只会保留最后一次匹配的结果(也就是ID=3对应的Array),所以表格所有行都显示同一个值。
  2. 模板语法错误:
    • 表格的<toddy>标签拼写错误,应为<tbody>
    • 表格中{{ data.id }}的data未定义,应该使用循环变量tech,即{{ tech.id }}

修正方案

1. 优化数据匹配逻辑(推荐用Map提升效率)

把ar2转换成以ID为键的Map,这样可以快速通过ID找到对应的关键词,避免双重循环的低效问题:

// 将ar2转为Map,key为id,value为对应的itemId
const ar2Map = new Map(this.ar2.map(item => [item.id, item.itemId]));

// 创建存储匹配结果的对象,key为ar1的id
this.matchedKeywords = {};
this.ar1.forEach(item => {
  // 按id取出匹配值,无匹配则显示空字符串
  this.matchedKeywords[item.id] = ar2Map.get(item.id) || '';
});

如果坚持用原有的双重循环,只需把matchedValues改成对象存储:

this.matchedKeywords = {}; // 改为对象,按id存储对应关键词
this.ar1.forEach((array1Item: any) => {
  this.ar2.forEach((array2Item: any) => {
    if (array1Item.id === array2Item.id) {
      this.matchedKeywords[array1Item.id] = array2Item.itemId;
    }
  });
});

2. 修正模板代码

<table>
  <thead>
    <tr>
      <th>ID</th>
      <th>Tech</th>
      <th>Key Words</th>
    </tr>
  </thead>
  <tbody> <!-- 修正标签拼写 -->
    <tr *ngFor="let tech of ar1">
      <td>{{ tech.id }}</td> <!-- 修正为循环变量tech的id -->
      <td>{{ tech.itemId }}</td>
      <td>{{ matchedKeywords[tech.id] }}</td> <!-- 根据当前行id取出对应关键词 -->
    </tr>
  </tbody>
</table>

效果说明

修改后,表格会根据每行的ID从matchedKeywords对象中取出对应的关键词,最终显示你期望的结果:

idtechkeyword
1HTMLTag
2CSSClasses
3JavaScriptArray

内容的提问来源于stack exchange,提问作者Danny

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 08:01:22