1

I have a an associative array in php that i parse to get json from it (json_encode) then i store the result in a javascript var

var myArray = <?php print json_encode($phpArray); ?>;

Now whene the user hit a button i should choose another element from the array dynamically, for example, i chose a random first element :

var an_element = myArray.a2.link;

-'a2' is an array in the main array

-'link' is an element in the a2 array.

So now whene the user hit my button, i want to choose a random other array id (for example a5, a9, etc.) I tried this :

var randomnumber=Math.floor(Math.random()*101); // choose random number
var newRandomArrayID= "a"+randomnumber;
an_element = myArray.newRandomArrayID.link;

It doesn't works, it says myArray.newRandomArrayID is undefined. Anyone can help? Thank you

john
  • 535
  • 7
  • 16
  • 2
    possible duplicate of [Dynamic object property name](http://stackoverflow.com/questions/4244896/dynamic-object-property-name) – Felix Kling Oct 10 '11 at 17:23

1 Answers1

6

You need to use [] indexing to find properties by name:

an_element = myArray[newRandomArrayID].link;

Otherwise JS is looking for a property actually called newRandomArrayID on myArray rather than using the value of the variable to lookup the property.

mellamokb
  • 56,094
  • 12
  • 110
  • 136
  • K.O Prefect it works :) i can't check it as answered till 10 min passe (stackoverflow rules) :p Thank you – john Oct 10 '11 at 17:26