-3

This sounds like a pretty simple one but I cannot use a "dynamic" variable to refer to an array. Say I wanted to pull up "Brent_Chart_1", to locate it in the array I would do something like this:

data[i].Brent_Chart_1

Suppose though I want to loop through a number of categories, and also wanted to pull up "WTI_Chart_1". I would want to do something like this:

$comm_array = array("Brent","WTI");

for(var comm; comm = comm_array.pop();){

...

data[i].eval(comm + "_Chart_1")

...

}

This, however, does not seem to work. How should I build this reference "dynamically"?

EDIT:

Here is further context on the issue:

if (data[i].ID == 39) {
    console.log(comm);
    $("#" + comm + "_Chart_1").highcharts('StockChart', jQuery.parseJSON(data[i][comm + '_Chart_1']));
} else {
    console.log(comm);
    $("#" + comm + "_Chart_1").highcharts(jQuery.parseJSON(data[i][comm + "_Chart_1"]));
}

comm + 1
}
Noobster
  • 1,024
  • 1
  • 13
  • 28
  • 1
    [Don't use eval needlessly!](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval#Don.27t_use_eval.21) – Rahil Wazir Jun 16 '14 at 16:59
  • You could use a while loop instead of a for loop in that instance, like `while(comm = comm_array.pop())` –  Jun 16 '14 at 17:01

2 Answers2

4

Use bracket notation like so:

data[i][comm + "_Chart_1"]
canon
  • 40,609
  • 10
  • 73
  • 97
1

I think data[i][comm + "_Chart_1"] will work

Maulik Vora
  • 2,544
  • 5
  • 28
  • 48
  • data[i]["Brent_Chart_1"] works, but not data[i][comm + "_Chart_1"] – Noobster Jun 16 '14 at 17:08
  • That is correct canon, and it did give me WTI first. The log returned the variables as expected ... namely Brent and WTI – Noobster Jun 16 '14 at 17:28
  • The array is built properly, as data[i]["Brent_Chart_1"] works... but not data[i][comm + "Brent_Chart_1"]. We have also established that comm is ok as it appears fine in the console log – Noobster Jun 16 '14 at 17:32
  • ALSO: I notice in the error log I get the following: "Uncaught SyntaxError: Unexpected end of input " – Noobster Jun 16 '14 at 17:37
  • canon, that was a typo, I meant [comm + "_Chart_1"]. I think the problem is that the code doesn't think comm is a sring. Is this because it has been pulled from an array? – Noobster Jun 16 '14 at 17:47