2016-06-29 10 views
27

このトピックに関するJavaScriptに関する質問を行ってきましたが、この質問は特にTypeScriptのAngular2についてです。2つのオブジェクト配列を角度2とTypeScriptでマージしますか?

私がしようとしているのは、jsonオブジェクトを配列に連結することです。

私のコードは次のようになり、

public results: []; 


public getResults(){ 
    this._service.get_search_results(this._slug, this._next).subscribe(
      data => { 
       this.results.concat(data.results); 
       this._next = data.next; 
      }, 
      err => { 
       console.log(err); 
      } 
     ); 
} 

は、どのように私はtypescriptですと角度でthis.resultsdata.resultsを連結することができますか?

this._slugおよびthis._nextがクラスに設定されています。

ありがとうございました。

答えて

48

私は次むしろあなたが使うべきだと思う:

data => { 
    this.results = this.results.concat(data.results); 
    this._next = data.next; 
}, 

concatdocから:

CONCAT()メソッドが呼び出された配列で構成される新しい配列を返します。引数として与えられた配列および/または値と結合される。

+0

残念ながら、これはUint8arraysでは動作しません。 –

27

スプレッドオペレータはちょっとクールです。

this.results = [ ...this.results, ...data.results]; 

スプレッド演算子を使用すると、簡単に別の配列に、配列の拡張バージョンを配置することができます。

You can read about spread operator here.

0

あなたはまた、ES6が推奨するフォームを使用することができます:あなたが最初の(public results = [];を)あなたの配列を初期化場合

data => { 
    this.results = [ 
    ...this.results, 
    data.results, 
    ]; 
    this._next = data.next; 
}, 

これは動作します。そうでなければ...this.results,...this.results ? this.results : [],に置き換えてください。

希望します。

関連する問題