Sharing a useful trick I discovered for passing variables into the scope of the JS Array.forEach() method.
I recently encountered a scenario where I needed to iterate through a loop to create a dataset. However, I also needed to access variables within the current scope, specifically being able to refer to 'this' in the loop.
Here's the setup I was dealing with:
var dataset = {
data: [],
backgroundColor:[],
};
items.forEach(function (item) {
dataset.data.push(item.age);
if (item.age < 2) {
dataset.bgColor.push(this.green);
} else if (item.age < 5) {
dataset.bgColor.push(this.yellow);
} else {
dataset.bgColor.push(this.red);
}
}, this);
this.refreshGraph(dataset);
The issue was that 'Dataset' was not accessible within the loop. So how could I access it while iterating?
I searched on stack overflow and couldn't find a suitable solution.
Read on for the answer: