Angular 5中如何提取JSON对象unit_1的值并遍历展示?
解决Angular 5中遍历JSON嵌套对象值的问题
嘿,作为Angular新手碰到这种嵌套对象的遍历问题太正常啦!别担心,给你个超简单的解决方案,完全不用复杂操作~
首先得明确:你的unit_1是一个普通JavaScript对象,而Angular的*ngFor默认只能遍历数组,所以我们需要把对象里的键或者值转换成数组,才能用*ngFor循环展示。
方案一:用Object.keys()遍历键,再取值(兼容性最好)
这个方法适合Angular 5这类相对早期的版本,因为Object.keys()是ES6就支持的方法,不需要额外配置polyfill。
第一步:在组件里写一个获取键的方法
在你的组件类中添加一个方法,用来提取unit_1的所有键:
getUnitKeys(unit: any): string[] { return Object.keys(unit); }
第二步:在模板中遍历展示
假设你已经用*ngFor遍历外层的学生数据,那在表格里可以这样写:
<table> <thead> <tr> <th>学生GUID</th> <th>时长(秒)</th> <th>会话次数</th> <!-- 生成Unit的表头 --> <th *ngFor="let key of getUnitKeys(students[0].unit_1)">Unit {{ key }}</th> </tr> </thead> <tbody> <tr *ngFor="let student of students"> <td>{{ student.student_guid }}</td> <td>{{ student.seconds }}</td> <td>{{ student.session_count }}</td> <!-- 遍历unit_1的每个值 --> <td *ngFor="let key of getUnitKeys(student.unit_1)"> {{ student.unit_1[key] }} </td> </tr> </tbody> </table>
方案二:直接提取值数组(更简洁,需注意兼容性)
如果你的项目已经配置了支持ES2017+的polyfill,也可以直接用Object.values()来获取值数组:
组件方法:
getUnitValues(unit: any): number[] { return Object.values(unit); }
模板里就可以直接遍历值:
<td *ngFor="let value of getUnitValues(student.unit_1)"> {{ value }} </td>
为什么这个方法可行?
因为Object.keys()会返回对象所有可枚举属性的键组成的数组(你的unit_1键是0-7,会自动按数字升序排列,刚好符合需求),然后我们通过student.unit_1[key]就能拿到对应的值。
这样就能轻松把unit_1里的所有值遍历到表格的<td>里啦,和你之前用*ngFor处理其他数据的逻辑保持一致,非常直观。
内容的提问来源于stack exchange,提问作者Neeraj
相关产品推荐
相关产品推荐

