2017-05-04 8 views
1

APIからオブジェクト結果をループし、配列にプッシュしたい。配列にデータをプッシュする方法ループオブジェクトの場合

historys: any = []; 

ループ。 this.historysよう

Object.keys(response['orderdetail']).forEach(function(index, key) { 
    console.log(key, response['orderdetail'][index]) 
    this.historys.push(response['orderdetail'][index]); 
}); 

ルックは、これを行う方法 、historys: any = [];ではありません。

+0

'this.historys.push'では' this'とは何ですか?あなたは '歴史 'をどこで定義しましたか? – Satpal

+0

実際にforEachのコールバックへの最初のparamはインデックスではありませんが、要素と2番目のインデックスはインデックス – binariedMe

答えて

2

この問題はforeach関数にあり、thisコンテキストが失われ、変更されています。 foreachの引数としてコンテキストを渡すことができます。

Object.keys(response['orderdetail']).forEach(function(index, key) { 
    console.log(key, response['orderdetail'][index]) 
    this.historys.push(response['orderdetail'][index]); 
}, this); 
// ^^^^ this will keep the this context 
+0

ですよ、ありがとう。 – ThunderBirdsX3

関連する問題