Iterate over array of objects in Typescript

Issue

I need to iterate over the array of objects in angular 2 and limit the string length display for a particular key in the object.

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');
        }
      }
    });
  } 

I need to limit the prod_desc length to (say) 10 characters while displaying for which I have used:

Eg:

this.product_desc.substring(0,10)

Solution

You can use the built-in forEach function for arrays.

Like this:

//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);
});

Your version wasn’t wrong though. It should look more like this:

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

Answered By – Spitzbueb

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published