迭代Typescript中的对象数组 [英] Iterate over array of objects in Typescript

查看:386
本文介绍了迭代Typescript中的对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

});
}

}); }

我需要将prod_desc长度限制为(比方说)10个字符,同时代替我使用的代码:

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

例如:

this.product_desc.substring(0,10)


推荐答案

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

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

像这样:

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

这篇关于迭代Typescript中的对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆