ThunderBirdsX3
ThunderBirdsX3

Reputation: 588

How to push data to array, When loop object

I want to loop object result from API, And push it in to array.

historys: any = [];

Loop.

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

Look like this.historys is not historys: any = [];, How to do this.

Upvotes: 1

Views: 86

Answers (1)

MrCode
MrCode

Reputation: 64526

This issue is in the foreach function, you've lost your this context and it has changed. You can pass the context as an argument to 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

Upvotes: 2

Related Questions