0

I have created with php several javascript array which are called as follows:

pricesArray_230
pricesArray_350
...etc...

I now want to access these arrays, but I have no clue how to include the dynamic part.

My code right now, which is not working:

newPrice = pricesArray_+productId+[currentSimpleProduct][0];

Where productId is the dynamic part and represents 230, 350, or any other number.

Do any of you have an idea how to dynamically call these arrays?

Jacob
  • 77,566
  • 24
  • 149
  • 228
Patrick Steenks
  • 612
  • 1
  • 11
  • 24

3 Answers3

3

To avoid eval, assuming that pricesArray_* are global variables, you can use:

window['pricesArray_' + productId][currentSimpleProduct][0]

Better yet, update your dynamically-generated code so it creates an object or array instead of variables:

var pricesArrays = {
    '230': {...},
    '350': {...},
    // etc
}
Jacob
  • 77,566
  • 24
  • 149
  • 228
3

If you're in the browser, and the variable is in the global scope, you can use bracket notation like:

foo = window['pricesArray_'+productId[currentSimpleProduct][0]]
djheru
  • 3,525
  • 2
  • 20
  • 20
1

You have to use eval:

newPrice = eval('pricesArray_' + productId)[currentSimpleProduct][0];

However, eval can be problematic, so I suggest using an object instead. This will require you to change your PHP code to output something like this:

var arrays = {
    product230 : [], // array here
    product350 : [] // array here, etc.
}

Then you can just use:

newPrice = arrays['product' + productId][currentSimpleProduct][0];
bfavaretto
  • 71,580
  • 16
  • 111
  • 150