我有这个JSON对象,它在数组内部显示为Json对象。所以我不能遍历它们。任何帮助,将不胜感激。下图显示了vs代码上显示的类型。我已将placeTypes初始化为[],但将其显示为{}。
InitialModel = [
{nearByTypeName : "ex 1",id: 1,placeTypes:[
{placeTypeId:1,placeTypeName:"ex1.1",
places:[]}
]},
{nearByTypeName : "ex 2",id: 2,placeTypes:[
{id:2,placeTypeName:"ex 2.1",places:[]},
{id:3,placeTypeName:"ex2.1.1",places:[]}
]}
]
答案 0 :(得分:3)
尝试这样:
const initialModel = [
{
nearByTypeName: "ex 1", id: 1, placeTypes: [
{
placeTypeId: 1, placeTypeName: "ex1.1",
places: []
}
]
},
{
nearByTypeName: "ex 2", id: 2, placeTypes: [
{ id: 2, placeTypeName: "ex 2.1", places: [] },
{ id: 3, placeTypeName: "ex2.1.1", places: [] }
]
}
];
for (const i of initialModel) {
for (const j of i.placeTypes) {
// do stuff
}
}
编辑:您声明要使用foreach循环,但由于以下错误而不能使用:
Error: Cannot invoke an expression whose type lacks a call signature
该错误是由类型不匹配引起的。这是由属性名称的差异引起的。如果您将数组第二个元素中的id
重命名为placeTypeId
,它将起作用
const initialModel = [
{
nearByTypeName: "ex 1", id: 1, placeTypes: [
{ placeTypeId: 1, placeTypeName: "ex1.1", places: [] }
]
},
{
nearByTypeName: "ex 2", id: 2, placeTypes: [
{ placeTypeId: 2, placeTypeName: "ex 2.1", places: [] },
{ placeTypeId: 3, placeTypeName: "ex2.1.1", places: [] }
]
}
];
initialModel.forEach(element => {
const temp = element.placeTypes;
temp.forEach(val => {
// do stuff
})
});
答案 1 :(得分:2)
这就是如何使用嵌套循环循环抛出
组件
InitialModel = [
{nearByTypeName : "ex 1",id: 1,placeTypes:[
{placeTypeId:1,placeTypeName:"ex1.1",
places:[
this.deepCopy()
]}
]},
{nearByTypeName : "ex 2",id: 2,placeTypes:[
{id:2,placeTypeName:"ex 2.1",places:[
this.deepCopy()
]},
{id:3,placeTypeName:"ex2.1.1",places:[
this.deepCopy()
]}
]}
]
deepCopy(){
return ['TRY','USA'].slice(0)
}
确保deepCopy返回数组
模板
<div *ngFor="let m of InitialModel">
{{m.nearByTypeName }}
<div *ngFor="let type of m.placeTypes">
{{type.placeTypeName}}
<div *ngFor="let place of type.places">
{{place}}
</div>
</div>
</div>