我正在尝试迭代对象的对象
这是我将得到的响应 json
{
"123445": {
"displayName": "abcd",
"items": [
{
"id": "e7363730-552d-4943-a3b8-082db653fc16",
"name": "xyz",
"displayName": "xyd",
"price": "75",
"quntity": "100"
},
{
"id": "302fda08-502d-4f5a-98b8-cbca34f8e186",
"name": "pqr",
"displayName": "pqr",
"price": "60",
"quntity": "100"
}
]
}
}
这是我正在尝试的
<div *ngFor="let key of generateKeys(products | async)">
<div *ngFor="let product of products[key].items | async">{{ product | json}}</div>
</div>
这是将从产品对象返回键的函数
generateKeys(obj) {
return obj ? Object.keys(obj) : null
}
但是在渲染 HTML 模板时出现错误
Cannot read property 'items' of undefined
我是否遗漏了什么,请提出建议。
最佳答案
根据我的理解,你可以尝试这个
模板
<ng-container *ngIf="products | async as products">
<div *ngFor="let key of generateKeys(products)">
<span>{{key}}</span>
<div *ngFor="let product of getProducts(products,key)">
<span>{{product.id}}</span>
</div>
</div>
</ng-container>
函数generateKeys将从对象返回键
generateKeys(obj) {
return obj ? Object.keys(obj) : null
}
函数 getProducts 将从产品中返回项目
getProducts(productsList, key: string) {
return key ? productsList[key].items : null
}
希望这能解决您的问题。
关于javascript - Angular 4迭代对象的对象以获得动态数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46703283/