【发布时间】:2014-01-14 18:13:57
【问题描述】:
所以这有点迷幻,但就这样吧。
假设我有两个数组——一个包含一组类别的一维数组和一个包含任意数量的数组的二维数组,这些数组的内容遵循第一个数组建立的类别模板。例如:
var categoryArray = ["Name", "Title", "Hire Date"];
var infoArray = [["John","Project Manager","January 5"], ["Alex","Accountant","December 15"], ["Joanne","Graphic Designer","August 26"]];
我想做的是将这些信息整合到一个对象中。所以我放弃了:
var myDict = {};
我的(显然是错误的)尝试是嵌套的 for 循环遍历每个数组并尝试用数组的内容填充 myDict 对象。它看起来像这样:
// Start by iterating by the length of the info array, so we assign a new sub-object to the myDict Object for each entry.
for (i = 0; i < infoArray.length; i++) {
// Each entry will be a new "row," like in a spreadsheet.
var row = String("row"+i);
// I'm guessing that the declaration below doesn't actually assign the "Row1", "Row2", etc as nested objects like I had intended, but just re-writes a child called "row"
myDict.row = {};
// Next we iterate through the number of categories we'll need-- and we'll pull from the length of our categoryArray so we can change the number of categories later.
for (x = 0; x < categoryArray.length; x++) {
// In theory, the first iteration of this will create a child of "row1" called "name," which will hold a value of "John" (so, the value stored infoArray[1][1])
myDict.row.categoryArray[x] = infoArray[i][x];
}
}
那里显然有很多错误,但我完全不知道如何解决这个问题。我想关键问题是试图将变量/数组保存的实际字符串分配为对象/子项的名称,但是彻底的谷歌搜索没有产生任何答案。
拯救我哦强大的互联网!
【问题讨论】:
-
互联网会让你刻录,直到你提供预期的结果:-) 请edit你的帖子并包含你想要得到的 JSON。
标签: javascript oop