1

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.

2
  • What does this refers to in this.historys.push? Where have you defined historys? Commented May 4, 2017 at 9:11
  • actually first param to callback of forEach is not index but element and second one is index Commented May 4, 2017 at 9:12

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.