2017-09-14 102 views
3

我需要遍歷角2中的對象數組,並限制對象中特定鍵的字符串長度顯示。遍歷Typescript中的對象數組

this.productService.loadAllProducts(product).subscribe(data => { 
    if (this.authService.checkActiveSession(data)) { 
    if (data.success) { 
    //console.log(this.product_desc.substring(0,2)) 
     for(let i=0;i<data.products.length ;i++){ //How to properly iterate here!! 
     console.log(data.products[0].product_desc) 
     } 
     this.source.load(data.products); 
    } else { 
     console.log('Not binded'); 
    } 
    } 

}); }

我需要限制prod_desc長度(比如說)10個字符,而displaing爲我所用:

如:

this.product_desc.substring(0,10) 

回答

6

您可以使用內置的forEach功能陣列。

像這樣:

//this sets all product descriptions to a max length of 10 characters 
data.products.forEach((element) => { 
    element.product_desc = element.product_desc.substring(0,10); 
}); 

你的版本是沒有錯的,但。它應該看起來更像這樣:

for(let i=0; i<data.products.length; i++){ 
    console.log(data.products[i].product_desc); //use i instead of 0 
}