Ionic报错Error trying to diff '[object Object]' 如何提取JSON的friend字段生成可遍历数组
报错原因说明
Error trying to diff '[object Object]'. Only arrays and iterables are allowed 报错是因为Ionic底层的Angular框架中,*ngFor 遍历指令仅支持数组、Set等可迭代类型,你当前绑定给*ngFor的变量是对象类型,所以触发校验报错。
friend字段提取实现方案
假设你拿到的接口JSON响应结构示例如下(可根据你的实际结构调整取值路径):
{ "code": 200, "data": { "contactList": [ {"id": 1, "remark": "同学", "friend": {"name": "张三", "phone": "13xxxxxxxxx"}}, {"id": 2, "remark": "同事", "friend": {"name": "李四", "phone": "15xxxxxxxxx"}} ] } }
- 第一步:在页面对应的ts文件中定义存储friend数据的空数组
// 可根据你的实际业务替换any为定义好的Friend类型 friendList: any[] = [];
- 第二步:接口请求成功后提取所有friend字段存入数组
// 假设接口返回的完整响应存在res变量中 this.friendList = res.data.contactList.map(item => item.friend); // 可选:过滤掉friend为null/undefined的空项,避免后续渲染异常 this.friendList = this.friendList.filter(Boolean);
- 第三步:HTML中直接遍历生成元素即可
<ion-list> <ion-item *ngFor="let item of friendList"> <ion-label>{{ item.name }}</ion-label> <ion-note slot="end">{{ item.phone }}</ion-note> </ion-item> </ion-list>
提示:如果你的JSON响应结构和示例不同,只需要调整
map方法中的取值路径,保证最终friendList是纯数组即可解决报错。
内容的提问来源于stack exchange,提问作者CoderTn
相关产品推荐
相关产品推荐

