Angular中遍历JSON对象数组并在表格展示指定字段的问题
解决你的Angular遍历与表格显示问题
嘿,作为Angular初学者遇到这些问题太正常了,我来一步步帮你搞定!
问题1:如何遍历JSON对象数组提取所有对象
先看你的JSON结构:返回的是一个包含单个对象的数组,而每个外层对象里又嵌套了一个treshold数组(里面才是你需要的具体数据对象)。
你已经通过HttpClient拿到了posts数组,提取对象分两种场景:
- 提取外层posts数组的对象:直接遍历
posts数组即可,比如用数组方法或循环:// 在subscribe回调里遍历外层对象 this.http.get('http://urladdress').subscribe(posts => { this.posts = posts; // 遍历每个外层post对象 this.posts.forEach(post => { console.log('外层post对象:', post); // 要是需要处理嵌套的treshold数组,继续遍历子数组 post.treshold.forEach(item => { console.log('treshold子对象:', item); }); }); }); - 提取所有嵌套的
treshold子对象:如果想把所有treshold里的对象合并成一个单独数组(方便后续表格展示),可以用flatMap方法:// 在component.ts里新增数组存储treshold子对象 tresholdItems: any[] = []; ngOnInit() { this.http.get<any[]>('http://urladdress').subscribe(posts => { this.posts = posts; // 合并所有post的treshold数组为一个数组 this.tresholdItems = posts.flatMap(post => post.treshold); }); }
问题2:表格显示[Object object]的解决方法
你现在的问题根源很明确:
post.treshold是一个数组,直接插值{{post.treshold}}会把数组转成字符串,所以显示[Object object]post.pointsToAdd根本不存在,这个字段是在treshold数组的每个子对象里,不是外层post的属性
我们用上面提到的tresholdItems数组来修改代码:
修改后的component.ts
export class TresholdComponent implements OnInit { posts: any[] = []; tresholdItems: any[] = []; // 专门存储所有treshold子对象 constructor(private http: HttpClient) {} ngOnInit() { this.http.get<any[]>('http://urladdress').subscribe(posts => { this.posts = posts; // 提取所有treshold子对象到单独数组 this.tresholdItems = posts.flatMap(post => post.treshold); }); } }
修改后的component.html
<table class="table table-borderless user-table"> <thead class="thead-border"> <tr> <div class="d-flex justify-content-center table-checkbox"> <mat-checkbox class=""></mat-checkbox> </div> <td scope="col">Treshold</td> <td scope="col">Points to add</td> </tr> </thead> <tbody> <!-- 遍历tresholdItems数组,每个item就是包含目标字段的对象 --> <tr *ngFor="let item of tresholdItems"> <div class="d-flex justify-content-center table-checkbox"> <mat-checkbox></mat-checkbox> </div> <td>{{item.treshold}}</td> <td>{{item.pointsToAdd}}</td> </tr> </tbody> </table>
这样修改后,表格就能正确展示treshold和pointsToAdd的值,不会再出现[Object object]啦!
内容的提问来源于stack exchange,提问作者turingox
相关产品推荐
相关产品推荐

