Multi-dimensional associative arrays in JavaScript -
there following query results: (key1 , key2 text)
id key1 key2 value 1 fred apple 2 2 mary orange 10 3 fred banana 7 4 fred orange 4 5 sarah melon 5 ...
and wish store data in grid (maybe array) looping records this:
apple orange banana melon fred 2 4 7 - mary - 10 - - sarah - - - 5
in php easy, using associative arrays:
$result['fred']['apple'] = 2;
but in javascript associative arrays doesn't work. after reading tons of tutorial, this:
arr=[]; arr[1]['apple'] = 2;
but arr['fred']['apple'] = 2;
doesn't work. tried arrays of objects, objects properties can't free text. more reading tutorials, more got confused...
any idea welcome :)
just use regular javascript object, 'read' same way associative arrays. have remember initialize them first well.
var obj = {}; obj['fred'] = {}; if('fred' in obj ){ } // can check presence of 'fred' if(obj.fred) { } // checks presence of 'fred' if(obj['fred']) { } // checks presence of 'fred' // following statements work obj['fred']['apples'] = 1; obj.fred.apples = 1; obj['fred'].apples = 1; // or build or initialize structure outright var obj = { fred: { apples: 1, oranges: 2 }, alice: { lemons: 1 } };
if you're looking on values, might have looks this:
var people = ['fred', 'alice']; var fruit = ['apples', 'lemons']; var grid = {}; for(var = 0; < people.length; i++){ var name = people[i]; if(name in grid == false){ grid[name] = {}; // must initialize sub-object, otherwise 'undefined' errors } for(var j = 0; j < fruit.length; j++){ var fruitname = fruit[j]; grid[name][fruitname] = 0; } }
Comments
Post a Comment