栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何在嵌套的json对象上执行ngFor循环?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何在嵌套的json对象上执行ngFor循环?

您在这里得到了一些不错的答案,但是所有人都在操纵您的响应并更改其构造,而不是按原样处理。您的响应中还有其他数据,并且希望保留这些数据,因此这是使用Pipe的解决方案。

You seem to have two objects in your array, but only one contains

routes
.
Will this always be the case? If not, you might want to iterate the response
and show all routes (if exists) for all objects, so I’d iterate the array
first, and then iterate the routes:

<!-- Iterate array --><div *ngFor="let obj of jsonData">  <!-- iterate routes for each object using pipe -->  <div *ngFor="let route of obj.routes | keys">    {{route.toCity}}  </div></div>

And then the keys pipe:

@Pipe({ name: 'keys',  pure: false })export class KeysPipe implements PipeTransform {    transform(value: any, args?: any[]): any[] {      // check if "routes" exists      if(value) {        // create instance vars to store keys and final output        let keyArr: any[] = Object.keys(value), dataArr = [];        // loop through the object,        // pushing values to the return array        keyArr.forEach((key: any) => { dataArr.push(value[key]);        });        // return the resulting array        return dataArr;      }    }}

This way you have not manipulated your response, and you have access to all
other data that is coming with the response.

Demo



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/380436.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号