| | Stumble It! | Add to Mixx! | | diigo it | | Slashdot |

Wednesday, June 3, 2009

Create Multidimensional Associative Arrays in Javascript

Wooh, that title is a mouthful!

I've been using arrays more and more in my code and found that I enjoy the ease of being able to reference my multidimensional arrays by names instead of by number. That is to say
alert(myArray['row3']['column4']);
instead of
alert(myArray[2][3]);
The term 'associative' means using words instead of numbers to find data in your arrays.

Sure, sure. the second method is shorter and therefore more elegant, but I found myself getting tired of having to scroll around my script to find the array that I needed to work with and figure out which index related to which column. It was just a big pain in the rear.

I knew that it was possible to create a one dimensional array and use words to reference particular rows of the array, but I had never seen an example of how to accomplish this in a multidimensional array.

I dug around on Google for a while and here's what I came up with. I'm assuming that you have your own method of populating the array, I'm just going to show you the structure for how to create a basic multidimensional associative array with JavaScript:
var myArray = new Array();
myArray['row1'] = { 'col1':'BLARGH!!!', 'col2':'HONK!!!!' }
myArray['row2'] = { 'col1':'FOO!!!', 'col2':'BAR!!!!' }
myArray['row3'] = { 'col1':'FOUR!!!', 'col2':'GREGS!!!' }

document.write(myArray['row2']['col1'] + " - " + myArray['row3']['col2']);
This will produce the following as output:
FOO!!! - GREGS!!!
So hopefully my overuse of the keywords has helped rank this page high in the search algorithms and you've found my tip useful. Remember though, it's only really useful if you have a do while or for loop to populate the array.

Enjoy!

3 comments:

Andrew Peters said...

Thanks for the help, trying to figure out the syntax was a rude awakening after doing the same thing in PHP for so long!

Julio Sampaio said...

hey guy thanks, it was very useful!

bunu said...

It is really good one