1

I'm trying to call an external variable in a forEach context. Since I'm using an arrow notation this should make the trick but the variable still comes out as undefined.

This is my code:

transformSlots (slots) {
 var array = slots;
 var newArray;
 array.forEach(element => {
   var newElement = {
     day: dateFns.getDate(element.slot),
     month: dateFns.getMonth(element.slot),
     year: dateFns.getYear(element.slot),
     hour: dateFns.getHours(element.slot),
     numInterview: element.num,
     id_users_pending: 0,
     id_users_accepted: 0
   };
   this.newArray.push(newElement);
 });
 return array;
}

EDIT: If I take .this away the result is exactly the same.

2
  • 4
    change this.newArray.push(newElement); to newArray.push(newElement); Commented Feb 15, 2019 at 6:56
  • 1
    newArray is only declared but not assigned any value like empty array. so. doing newArray.push(newElement); will also be wrong. instarting it should be var newArray = [] then, newArray.push(newElement); Commented Feb 15, 2019 at 10:17

2 Answers 2

1

Remove the this. It will make the code look for newarray in the callback and not outside the loop

transformSlots (slots) {
 var array = slots;
 var newArray;
 array.forEach(element => {
   var newElement = {
     day: dateFns.getDate(element.slot),
     month: dateFns.getMonth(element.slot),
     year: dateFns.getYear(element.slot),
     hour: dateFns.getHours(element.slot),
     numInterview: element.num,
     id_users_pending: 0,
     id_users_accepted: 0
   };
   newArray.push(newElement);
 });
 return array;
}

Sign up to request clarification or add additional context in comments.

Comments

0

You should use newArray.push(newElement); instead of this.newArray.push(newElement);.

If you print this in the forEach loop you'll find that the newArray isn't bind to this.

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.