I know there are some related posts and I have gone through them, but I have not been able to make my code work. The provided code is a simplified portion of a larger code base. As you can see below, there is a for loop through the array of JSON objects, and inside that for loop there is a function call that returns the Y coordinates. We decide what to return, based on a property (flag) from each JSON object in the array - "invert". It's an angularJS code, built upon angular-nvd3 charts, but I believe the issue here is in how JS generally handles loops and nested function calls.
Can I directly access the "invert" property of array items from the function body within each iteration or is it technically impossible?
var listOfOptions = [];
for (var j = 0; j < arrayOfJSONObjects.length; j++) {
// assuming arrayOfJSONObjects has only two elements,
// when the loop finishes, j is going to be equal to 2
var options = {
isInverted: arrayOfJSONObjects[j].invert,
// here all works well, we get the "invert"
// property from each loop step into each "options" object
chart: {
type: 'lineChart',
height: arrayOfJSONObjects[j].height,
y: function (d) {
console.log(j);
// here there is already an issue, j
// always appears as 2, meaning that
// the loop has already completed
console.log(arrayOfJSONObjects[j].invert);
// same issue here, it always outputs the
// invert property of the last (second) element in
// the list - arrayOfJSONObjects[1].invert
if (arrayOfJSONObjects[j].invert == 1) {
return (d.y * (-1));
}
else {
return d.y;
}
} // end y
} // end chart
}; // end options
listOfOptions.push(options);
} // end for