JavaScript associative arrays

Javascript associative arrays

I was struggling a bit to find something similar to PHP associative arrays that I could use in JavaScript. I like to use them to create hierachies. Here is a quick example of what we can do using them:

var myArray = new Array();
//Create root
myArray["Vehicles"] = new Array();

//Level 1 – create a “Car” level and add first element
myArray["Vehicles"] = {“Cars”: ["Audi"]};

// Add children to level 2;
myArray["Vehicles"]["Cars"].push(“GM”);
myArray["Vehicles"]["Cars"].push(“Mercedes”);
myArray["Vehicles"]["Cars"].push(“Porsche”);

// Add children to level 1
myArray["Vehicles"]["Trucks"] = new Array();
// Add children to level 2
myArray["Vehicles"]["Trucks"] = [["Iveco"], ["Volvo"]];
//Add child level 0
myArray["Parts & Accessories"] = new Array();
//Add children level 1 & 2
myArray["Parts & Accessories"]["Wheels"] = [["5 Zingen"], ["AMG"], ["HP Design"]];
myArray["Parts & Accessories"]["BullBars"] = [["16x12"], ["16x18"]];

for (key0 in myArray){
document.write(“<ul><li>” + key0 + “</li><ul>”);
for (key1 in myArray[key0]){
document.write(“<ul><li>” + key1 + “</li>\n<ul>”);
for (i=0;i < myArray[key0][key1].length;i++){
document.write(“<li>” + myArray[key0][key1][i] + “</li>”);
}
document.write(“</ul></ul>”);
}
document.write(“</ul></ul>”);
}

This version is a little bit simplified as we suppose we know how deep the hierarchy is. You may not know it in advance. You then need to add some tests. Anyway here is the final result of what the script produces:

  • Vehicles
    • Cars
      • Audi
      • GM
      • Mercedes
      • Porsche
    • Trucks
      • Volvo
      • Iveco
  • Parts & Accessories
    • Wheels
      • 5 Zingen
      • AMG
      • HP Design
    • Bullbars
      • 16×12
      • 16×18

As you can see, JavaScript will accept spaces in keys which may be convenient in some cases. I hope it helped someone. Cheers, Damien Goor.

Posted in JavaScript | Tagged | Leave a comment