Angular中对比数组并在表格展示匹配值的问题排查
问题分析与解决方案
问题根源
- 变量覆盖问题:你定义的
matchedValues是单个变量,每次匹配到对应ID时都会用新值覆盖旧值,循环结束后它只会保留最后一次匹配的结果(也就是ID=3对应的Array),所以表格所有行都显示同一个值。 - 模板语法错误:
- 表格的
<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对象中取出对应的关键词,最终显示你期望的结果:
| id | tech | keyword |
|---|---|---|
| 1 | HTML | Tag |
| 2 | CSS | Classes |
| 3 | JavaScript | Array |
内容的提问来源于stack exchange,提问作者Danny
相关产品推荐
相关产品推荐

