Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate over array of objects in Typescript

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 displaing for which i have used:

Eg:

this.product_desc.substring(0,10) 
like image 861
Sushivam Avatar asked Sep 14 '17 08:09

Sushivam


People also ask

How do I iterate through an array of objects in TypeScript?

To iterate over array of objects in TypeScript, we can use the for-of loop. to loop through the products array. product is the object being iterated through, so we can get the productDesc property from the object.

How do I iterate over objects in TypeScript?

Use let k: keyof T and a for-in loop to iterate objects when you know exactly what the keys will be. Be aware that any objects your function receives as parameters might have additional keys. Use Object. entries to iterate over the keys and values of any object.

How do you iterate through an array of objects?

To iterate through an array of objects in JavaScript, you can use the forEach() method aong with the for...in loop. The outer forEach() loop is used to iterate through the objects array.


2 Answers

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 } 
like image 172
Spitzbueb Avatar answered Sep 27 '22 18:09

Spitzbueb


In Typescript and ES6 you can also use for..of:

for (var product of products) {      console.log(product.product_desc) } 

which will be transcoded to javascript:

for (var _i = 0, products_1 = products; _i < products_1.length; _i++) {     var product = products_1[_i];     console.log(product.product_desc); } 
like image 37
Hubert Schumacher Avatar answered Sep 27 '22 18:09

Hubert Schumacher