有以下查询结果:(key1和key2可以是任何文本)
id key1 key2 value 1 fred apple 2 2 mary orange 10 3 fred banana 7 4 fred orange 4 5 sarah melon 5 ...
我希望将数据存储在网格(可能是数组)中,像这样 循环 所有记录:
apple orange banana melon fred 2 4 7 - mary - 10 - - sarah - - - 5
在PHP中,使用关联数组非常容易:
$result['fred']['apple'] = 2;
但是在JavaScript这样的关联数组中不起作用。阅读大量教程之后,我所能得到的就是:
arr=[]; arr[1]['apple'] = 2;
但arr['fred']['apple'] = 2;不起作用。我尝试了对象数组,但是对象属性不能是自由文本。我阅读教程的时间越长,我就越困惑。
arr['fred']['apple'] = 2;
任何想法都欢迎:)
只需使用常规的JavaScript对象,该对象将“读取”与关联数组相同的方式。您还必须记住先初始化它们。
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 work obj['fred']['apples'] = 1; obj.fred.apples = 1; obj['fred'].apples = 1; // or build or initialize the structure outright var obj = { fred: { apples: 1, oranges: 2 }, alice: { lemons: 1 } };
如果要查看值,则可能会有类似以下内容:
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; } }