I am trying to use a dynamically updated accessor for a javascript array inside of an object literal constructor. Both data and index variables are in the same functional scope.
var data = [];
var index = 0;
dateKeys.forEach(element=>{
data.push({"date":element,[otherKeys[0]]:currentAccount[index]["2017_Q1"],[otherKeys[1]]:0,[otherKeys[2]]:0,[otherKeys[3]]:0,[otherKeys[4]]:0,[otherKeys[5]]:0})
index = index +1;
})
The code above produces the following error message: TypeError: undefined is not an object (evaluating 'currentAccount[index]["2017_Q1"]')
Yet when I try:
dateKeys.forEach(element=>{
var index = 0;
data.push({"date":element,[otherKeys[0]]:currentAccount[index] ["2017_Q1"],[otherKeys[1]]:0,[otherKeys[2]]:0,[otherKeys[3]]:0,[otherKeys[4]]:0,[otherKeys[5]]:0})
index = index +1;
})
I get the correct data for index 0 but it does not update. Why does the scoping seem to make a difference here to the ability to use a variable name in place of a number in the square brackets? I have tried using let, to see if it was a binding issue, but that makes no difference. Is there a solution using vanilla javascript?
currentAccount,otherKeysordateKeysare. See minimal reproducible example for help on how to write an answerable question.