迭代Typescript中的对象数组

时间:2021-07-25 14:26:46

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.

我需要以角度2迭代对象数组,并限制对象中特定键的字符串长度显示。

 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:

我需要将prod_desc长度限制为(例如)10个字符,同时替换我使用过的:

Eg:

例如:

this.product_desc.substring(0,10)

1 个解决方案

#1


21  

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

您可以对数组使用内置的forEach函数。

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
}

#1


21  

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

您可以对数组使用内置的forEach函数。

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
}