[英]Angular2,Ionic2:How to access an array of objects inside another array of objects in typescript?
我對在angular2中使用數組的概念完全陌生。 我的JSON數據來自后端,該后端存儲在名為“ arr”的數組中。 但是我想訪問一個數組,該數組存在於“ arr”中的每個對象中,即“ arr”中的每個對象都有一個其中包含一些元素的數組。 我想在我的.ts文件而不是HTML文件中訪問該數組。 我需要對.ts文件中的內容進行一些修改,因此我想知道如何為該文件創建管道。
我讀到我們需要使用管道,但是我不明白如何使用管道。 如果您可以在圖片中看到,則有一個包含3個對象的主數組,這3個對象中的每一個都有一個名為category的數組,該數組又具有對象。 我想訪問主數組中存在的所有3個對象的類別內的“類別”字段。 有人可以幫我嗎?
如果在html中
<div *ngFor="let item of arr">
{{item.aliasname}}
<div *ngFor="let category of item.categories">
{{category.name}}
</div>
</div>
在類型腳本中,您可以使用foreach循環
arr.forEach(element => {
element.forEach(category => {
console.log(category.name);
// Do whatever you want
// You can access any field like that : category.yourField
});
});
這里不需要管道,管道將用於實際顯示模板中的數據,例如,如果您需要迭代對象鍵(不能與*ngFor
一起使用)。 但是,由於您要操縱組件中的數據...。
您需要兩個forEaches
才能到達不同對象內的每個類別。 並且,您需要在收到數據后從回調(訂閱)中執行此操作,這是有關此信息的更多信息: 如何從angular2中的Observable / http / async調用返回響應?
我建議您在服務中執行http請求,並訂閱組件中的數據,因此在您的組件中,調用該服務方法並訂閱響應,然后使用forEach:
ngOnInit() {
this.service.getData()
.subscribe(data => {
this.searchResults = data;
// call method or manipulate data here since response has been received
this.manipulateData();
});
}
manipulateData() {
this.searchResults.forEach((x:any)=> { // iterate outer array
x.categories.forEach((y:any) => { // iterate the categories of each object
console.log(y.name) // ... or whatever properties you have
// manipulate your data
})
})
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.