Acessing javascript multidimensional array with linear values
-
05-07-2019 - |
Question
How could I set a variable that I can read by using eval('productOptionTree' + '[0][1][0]')
?
(the '[0][1][0]' part comes from another variable)
UPDATE it's an ugly question, but I couldn't find another way to do it. the only answer I could find is:
newVal = 4;
dim = '[0][1][0]';
eval('productOptionTree'+dim+' = ' +newVal);
Solution
You don't need eval to read the item. Just do:
var x = productOptionTree[product[0]][product[1]][product[2]];
As you are free of eval, you can now easily use the same way to set the item:
productOptionTree[product[0]][product[1]][product[2]] = 42;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow