2017-02-23 62 views
-1

我有一個對象的對象內,我想到內一個到一個字符串分隔逗號轉換,但它產生一個無限循環在angular2打字稿的對象轉換爲一個數組

可觀察到的HTTP請求之後正在逐漸以此方式,數據

this._categoryService.getChecklistCategories() 
    .subscribe(
    res => { 
     this.categories = res; 
     let newitem:string[]; 
     for(var i=0; i<res.length; i++){ 
     this.categories.map((category, i) => category.no = i+1); 
     var obj = res[i].assigned; //an obect. 
     console.log(obj[0]); //get the first index 
    } 
    }) 

上面的console.log(OBJ [0])生成

enter image description here

我會升IKE創建truck_subtype的字符串,並將其追加到this.categories

我曾嘗試以下

 res => { 
     this.categories = res; 
     let newitem:string[]; 
     for(var i=0; i<res.length; i++){ 
      this.categories.map((category, i) => category.no = i+1);//this adds no i,2,3... 
      var obj = res[i].assigned; //array item 
      let stringArray: Array<any> = []; 
      for(var i=0; i<obj.length; i++){ 
        stringArray.push(obj[i].truck_subtype); 

      } 
      this.categories.map((category, i) => category.assigned= stringArray)     

     } 
    } 

上面產生一個無限循環,未能陣列的字符串添加到this.categories

我在哪裏我錯了

+0

可能是被宣佈兩次(在和地圖()),我覺得你的指數不會繼續執行'res.length'因爲當您使用映射你辭職吧'i'變量。 – vinagreti

回答

0

可能是四次聲明的i變量(在for和map中),我認爲你的索引永遠不會到達res.length,因爲當你使用map時,你是resignin克它。

嘗試將i的內部映射更改爲另一個名稱,如i2 ...,並測試它以查看循環是否消失。

res => { 
    this.categories = res; 
    let newitem:string[]; 
    for(var i=0; i<res.length; i++){ 
     this.categories.map((category, i2) => category.no = i+1);//this adds no i,2,3... 
     var obj = res[i].assigned; //array item 
     let stringArray: Array<any> = []; 
     for(var i3 =0; i<obj.length; i++){ 
       stringArray.push(obj[i3].truck_subtype); 

     } 
     this.categories.map((category, i4) => category.assigned= stringArray)     

    } 
}