I am facing an issue with a foreach loop in my code. I have a new temp array created within the loop, followed by a nested foreach loop. However, when trying to access the temp array inside the nested loop, I encounter a "variable not available" error.
let final = {
array: []
};
myArray.forEach(item =>
{
let newObject = { items: [] };
item.subArray.forEach(subItem =>
{
var subObject = { prop: subItem.prop };
// Error here: "newObject is not available"
newObject.items.push(subObject);
});
// Error here: "final is not available"
final.array.push(newObject);
});
I understand that I could pass this
as an argument to make the array accessible (eg:
item.subArray.forEach(subItem => {},
this
);
)
However, this solution doesn't work for me since tempArray is not defined at the class level.
I encounter the same problem when attempting to assign my temp array to the "final" array declared outside the foreach loop.
Is there a way to access the parent scope from within the foreach loop?
It's worth mentioning that this code is part of a function within a class. My goal is to aggregate properties with a specific value from within the subarray.
Screenshot demonstrating the issue: https://i.stack.imgur.com/hawoz.png
(The code visible in the image is within the first forEach
loop)
Update: I managed to resolve this issue by addressing the use of let
and var
. Refer to my answer below for more information.