0

I'm attempting to reference a value in an array through the use of a variable.

So, given myarray, I can do the following just fine:

alert(myarray[1].hp_id);

The contents I'm after comes out just fine.

However, if I want to put hp_id in a variable, it doesn't work so well.

var array_col = hp_id;
alert(myarray[1].array_col);

How might I be able to make reference to an array value by using a variable?

Many thanks in advance.

neanderslob
  • 2,633
  • 6
  • 40
  • 82

2 Answers2

2

You should be able to do it this way

var array_col = 'hp_id';
alert(myarray[1][array_col]);
Robbert
  • 6,481
  • 5
  • 35
  • 61
1

using "dot notation" to reference key names only references things with that literal name, as though you were doing myarray[1]["array_col"]. Use myarray[1][array_col] to use a variable for the key name.

Eric Hannum
  • 382
  • 2
  • 6
  • 16