【问题标题】:Combine arrays into nested objects将数组组合成嵌套对象
【发布时间】: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];
    }
}

那里显然有很多错误,但我完全不知道如何解决这个问题。我想关键问题是试图将变量/数组保存的实际字符串分配为对象/子项的名称,但是彻底的谷歌搜索没有产生任何答案。

拯救我哦强大的互联网!

【问题讨论】:

标签: javascript oop


【解决方案1】:
var result = infoArray.map(function(currentArray) {
    return categoryArray.reduce(function(previous, currentKey, index) {
        previous[currentKey] = currentArray[index];
        return previous;
    }, {});
});

输出

[ { Name: 'John',
    Title: 'Project Manager',
    'Hire Date': 'January 5' },
  { Name: 'Alex',
    Title: 'Accountant',
    'Hire Date': 'December 15' },
  { Name: 'Joanne',
    Title: 'Graphic Designer',
    'Hire Date': 'August 26' } ]

如果你的环境不支持Array.prototype.map功能,可以使用这个

var result = [];
for (var i = 0; i < infoArray.length; i += 1) {
    var tempObj = {};
    for (var j = 0; j < categoryArray.length; j += 1) {
        tempObj[categoryArray[j]] = infoArray[i][j];
    }
    result.push(tempObj);
} 

【讨论】:

    【解决方案2】:

    使用row0、row1 等听起来不是一个好主意。数组会更有意义。无论如何:

    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 (i = 0; i < infoArray.length; i++) {
        // Each entry will be a new "row," like in a spreadsheet. 
        var row = {};
        myDict["row"+i] = 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])
            row[categoryArray[x]] = infoArray[i][x];
        }
    }
    

    输出:

    {
        "row0": {
            "Name": "John",
            "Title": "Project Manager",
            "Hire Date": "January 5"
        },
        "row1": {
            "Name": "Alex",
            "Title": "Accountant",
            "Hire Date": "December 15"
        },
        "row2": {
            "Name": "Joanne",
            "Title": "Graphic Designer",
            "Hire Date": "August 26"
        }
    }
    

    【讨论】:

      【解决方案3】:
      // 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 = {};
      

      没错。为此,您将不得不使用

       myDict[row] = {};
      

      (下面同样:myDict[row][…] = …)

      // 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];
      

      再次.categoryArray[x] 在这里用作文字属性名称(属性"categoryArray" 的属性x,它不存在) - 你将不得不wrap it in brackets。

      你应该得到:

      var myDict = {};
      for (var i = 0; i < infoArray.length; i++) { // make iteration variables local
                                                   // with "var"
          var row = "row"+i; // explicit String() call not necessary
          myDict[row] = {};
          for (var x = 0; x < categoryArray.length; x++) { // again, local "x"
              myDict[row][categoryArray[x]] = infoArray[i][x];
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-06-14
        • 1970-01-01
        • 2021-11-17
        • 1970-01-01
        • 1970-01-01
        • 2021-08-09
        • 2017-05-09
        相关资源
        最近更新 更多