Multi-dimensional associative arrays in JavaScript Multi-dimensional associative arrays in JavaScript javascript javascript

Multi-dimensional associative arrays in JavaScript


Just use a regular JavaScript object, which would 'read' the same way as your associative arrays. You have to remember to initialize them first as well.

var obj = {};obj['fred'] = {};if('fred' in obj ){ } // can check for the presence of 'fred'if(obj.fred) { } // also checks for presence of 'fred'if(obj['fred']) { } // also checks for presence of 'fred'// The following statements would all workobj['fred']['apples'] = 1;obj.fred.apples = 1;obj['fred'].apples = 1;// or build or initialize the structure outrightvar obj = { fred: { apples: 1, oranges: 2 }, alice: { lemons: 1 } };

If you're looking over values, you might have something that looks like this:

var people = ['fred', 'alice'];var fruit = ['apples', 'lemons'];var grid = {};for(var i = 0; i < people.length; i++){    var name = people[i];    if(name in grid == false){        grid[name] = {}; // must initialize the sub-object, otherwise will get 'undefined' errors    }    for(var j = 0; j < fruit.length; j++){        var fruitName = fruit[j];        grid[name][fruitName] = 0;    }}


If it doesn't have to be an array, you can create a "multidimensional" JS object...

<script type="text/javascript">var myObj = {     fred: { apples: 2, oranges: 4, bananas: 7, melons: 0 },     mary: { apples: 0, oranges: 10, bananas: 0, melons: 0 },     sarah: { apples: 0, oranges: 0, bananas: 0, melons: 5 } }document.write(myObj['fred']['apples']);</script>


Javascript is flexible:

var arr = {  "fred": {"apple": 2, "orange": 4},  "mary": {}  //etc, etc};alert(arr.fred.orange);alert(arr["fred"]["orange"]);for (key in arr.fred)    alert(key + ": " + arr.fred[key]);