1. ホーム
  2. javascript

[解決済み] Typescript でオブジェクトの配列を繰り返し処理する。

2023-02-21 14:17:50

質問

angular2のオブジェクトの配列に対して反復処理を行い、オブジェクト内の特定のキーに対する文字列長の表示を制限する必要があります。

 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
}