![](/img/trans.png)
[英]Angular Javascript object with arrays, looping through and getting length of each array?
[英]How to loop through an array of objects, loop through each object and push each object into separate arrays for ngFor looping in angular
我正在處理一個 Angular 7 項目,我正在處理一個 api,它在搜索時返回一組(食譜)對象,我想從每個對象中獲取所有成分,以便我可以遍歷它們,只獲取我想要的,因為每個(配方)對象都與另一個不同
我嘗試遍歷對象的初始數組,然后遍歷每個單獨的對象,只獲取每個(配方)對象的可用成分,但我不知道如何將它們推送到單獨的數組中。 每當我推送時,所有對象的所有成分都會被推送到一個數組中。
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { RecipesService } from 'src/app/services/recipes.service';
@Component({
selector: 'app-search',
templateUrl: './search.component.html',
styleUrls: ['./search.component.scss']
})
export class SearchComponent implements OnInit {
s: string;
ingArray: any[] = []
measurementsArr = []
nothingFound = false;
itemsFound = false;
searchedData: any[] = [];
searchresults: number;
constructor(private route: ActivatedRoute, private service:RecipesService) { }
ngOnInit() {
this.route.queryParams.subscribe(params=>{
this.s = params.s;
console.log(this.s)
})
this.searchDB()
}
searchDB(){
this.service.searchRecipeDB(this.s).subscribe((res:any)=>{
if(res.meals === null){
this.nothingFound = true;
}else{
this.searchedData = res.meals
console.log(this.searchedData)
this.itemsFound = true;
this.searchresults=this.searchedData.length;
let resultsarray = this.searchedData
for(let y of resultsarray){
for(let obj in y){
if(obj.includes('strIngredient')){
if(y[obj]!=null){
if(y[obj].length > 0){
this.ingArray.push(y[obj])
console.log(this.ingArray)
}
}
}
}
}
}
})
}
}
我已經能夠循環並從每個(配方)對象中獲取每種成分,但無法將它們推送到單獨的數組中而不必定義多個數組。 有沒有一種方法可以將(食譜)對象中的所有成分推送到單獨的數組中,而無需添加其他(食譜)對象中的其他成分? 我不想定義多個數組,因為我正在使用 api 並且我不知道預期的搜索結果一直顯示一組對象的搜索結果
for(let y of resultsarray){
ingrSub: Array<any> = new Array();
for(let obj in y){
if(obj.includes('strIngredient')){
if(y[obj]!=null){
if(y[obj].length > 0){
ingrSub.push(y[obj])
console.log(this.ingArray)
}
}
}
}
if(ingrSub.length > 0)
this.ingArray.push(ingrSub)
else
ingrSub = null;//just to be sure that we do not leak the memory if engine thinks the oposite in some case
}
只推 obj,而不是 y[obj]。 也許,我不明白這個任務。 並使用 of 而不是 in。或者您想從對象中獲取一些成分子字符串嗎?
this.array_a = [] <- this add your array this.array_b.forEach(array_b_item => { array_b_item.new_variable = JSON.parse( JSON.stringify(this.array_a) ); }); you can add values indivualy to array_b
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.