我有一个嵌套对象:
data = [
{
"id": "0001",
"type": "donut",
"name": "Cake",
"ppu": 0.55,
"batters":
{
"batter":
[
{ "id": "1001", "type": "Regular" },
{ "id": "1002", "type": "Chocolate" },
{ "id": "1003", "type": "Blueberry" },
{ "id": "1004", "type": "Devil's Food" }
]
},
"topping":
[
{ "id": "5001", "type": "None" },
{ "id": "5002", "type": "Glazed" },
{ "id": "5005", "type": "Sugar" },
{ "id": "5007", "type": "Powdered Sugar" },
{ "id": "5006", "type": "Chocolate with Sprinkles" },
{ "id": "5003", "type": "Chocolate" },
{ "id": "5004", "type": "Maple" }
]
},
{
"id": "0002",
"type": "donut",
"name": "Raised",
"ppu": 0.55,
"batters":
{
"batter":
[
{ "id": "1001", "type": "Regular" }
]
},
"topping":
[
{ "id": "5001", "type": "None" },
{ "id": "5002", "type": "Glazed" },
{ "id": "5005", "type": "Sugar" },
{ "id": "5003", "type": "Chocolate" },
{ "id": "5004", "type": "Maple" }
]
},
{
"id": "0003",
"type": "donut",
"name": "Old Fashioned",
"ppu": 0.55,
"batters":
{
"batter":
[
{ "id": "1001", "type": "Regular" },
{ "id": "1002", "type": "Chocolate" }
]
},
"topping":
[
{ "id": "5001", "type": "None" },
{ "id": "5002", "type": "Glazed" },
{ "id": "5003", "type": "Chocolate" },
{ "id": "5004", "type": "Maple" }
]
}
]
我想穿越这个对象并使用*ngFor
在我的HTML中显示batter
对象数据,但是当我嵌套*ngFor
以实现相同的情况时:
<div *ngFor="let item of data">
<!--Display first level elements here-->
<div *ngFor="let batter of item.batters">
<!--Display secondlevel elements here-->
</div>
</div>
我遇到以下错误说
Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.
如何将此嵌套对象转换为嵌套数组?还是有一种更好的方法可以使用Typescript/ecmascript/rxjs弄平此对象?
发生,因为您尝试在循环中迭代对象,而不是数组,请在这里查看:
"batters":{
"batter":
[
{ "id": "1001", "type": "Regular" }
]
},
这可以简化,我相信这种输出格式:
"batters":[
{ "id": "1001", "type": "Regular" },
{ "id": "1002", "type": "Regular" }
]
它看起来更好,并且在您的情况下会起作用。
简单:
let part = "batters":
{
"batter":
[]}
let extract = part["betters"]["batter"];
mainOrray["betters"] = extract;
编辑之后:JSON结构看起来很奇怪。要迭代槽糊,我想应该是这样的。
<div *ngFor="let item of data">
<div *ngFor="let i of item.batters.batter">
{{i.id}}, {{i.type}
</div>
</div>