我需要迭代angular 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');
    }
  }

});

我需要将prod_desc长度限制为(比如)10个字符,同时显示我使用的:

如:

this.product_desc.substring(0,10)

推荐答案

可以对数组使用内置的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
}

Typescript相关问答推荐

当类型不能undefined时,如何使编译器抛出错误?

物料UI图表仅在悬停后加载行

TS 2339:属性切片不存在于类型DeliverableSignal产品[]上>'

JS Redux Devtools扩展不工作

为什么typescript要把这个空合并转换成三元?

如何修复正在处理类型但与函数一起使用时不处理的类型脚本类型

在NextJS中获得Spotify Oauth,但不工作'

与字符串文字模板的结果类型匹配的打字脚本

Angular 错误NG0303在Angular 项目中使用app.Component.html中的NGFor

Vue SFC中的多个脚本块共享导入的符号

STypescript 件的标引签名与功能签名的区别

错误TS2403:后续变量声明必须具有相同的类型.变量';CRYPTO';的类型必须是';CRYPATO';,但这里的类型是';CRYPATO';

为什么TypeScrip不能解析对象析构中的赋值?

将接口映射到交叉口类型

编剧- Select 下拉框

类型判断数组或对象的isEmpty

React Context TypeScript错误:属性';firstName';在类型';iCards|iSearch';

记录的子类型<;字符串,X>;没有索引签名

有没有一种简单的方法可以访问Keyboard Shortcuts JSON文件中列出的每个命令的显示名称(标题)?

两个子组件共享控制权