0

I want to use dynamic chart names while using setExtremes (like chart1, chart2, chart3).

Instead of the below line as chart1

chart1.yAxis[0].setExtremes(min, max); // which works fine if used

I use the below line in order to have a dynamic chart name. But says properties of undefined.

'chart' + idconvertedtostr.yAxis[0].setExtremes(min, max); // does not work

'chart' + idconvertedtostr is not recognized as 'chart1'. What is wrong here?

My Code:

ID = parseInt(elem.getAttribute('id')) 
var idconvertedtostr = ID.toString();
console.log("ID", ID) // returns 1
console.log("join", 'chart' + idconvertedtostr) // returns chart1
'chart' + idconvertedtostr.yAxis[0].setExtremes(min, max); // throws error, not recognized as chart1.setExtremes(min, max)
Michael M.
  • 10,486
  • 9
  • 18
  • 34
Sarahrb
  • 407
  • 11
  • 24
  • Which chart library are you using? – CuriousMind Oct 21 '22 at 13:22
  • 1
    You *can* combine variable names (not like this, but using functions like "eval" or window[...] if its in the global scope) BUT this is a terrible idea: https://stackoverflow.com/questions/5187530/variable-variables-in-javascript – LeoDog896 Oct 21 '22 at 13:22
  • Create an *array* of charts and access them like `charts[ID]`… – deceze Oct 21 '22 at 13:25

1 Answers1

1

I would highly discourage doing it this way. If anything, you can use an array to store your charts (or better yet, dynamically make it in the array -- for the sake of simplicity, ill do it this way.).

const charts = [
  chart1,
  chart2,
  chart3
]

// then access a chart of an ID:

const ID = 1
// we subtract 1 because of array indexing: array[0] gives the first element
charts[ID - 1] // chart1

Though this is a terrible idea, you can also use window to get a global variable by its name:

window["chart1"] // returns chart1 (the variable)
LeoDog896
  • 3,472
  • 1
  • 15
  • 40