0

我正在尝试在所有具有动态属性名称和属性的对象中动态创建对象。这是一个示例:

工作:

|  name  |  job  |  building  |
 -----------------------------
|  adam  |  mop  |  school    |
|  adam  | teach |  school    |
|  eve   | cook  |  kitchen   |
|  eve   |  mop  |  house     |

数据名称:

| name  |
---------
| adam  |
| eve   |

期望的结果:

names = {
    adam: {
        school: ["mop", "teach"] 
    },
    eve: {
        kitchen: ["cook"],
        house: ["mop"]
    }
}

该脚本用于google的app脚本中,所以不能使用eval()之类的函数。这是我当前的代码:

  namesSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('dataNames');
  namesValues = namesSheet.getDataRange().getValues();
  jobsSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('jobs');
  jobsValues = rolesSheet.getDataRange().getValues();
  jobsNumRows = rolesRange.getNumRows();

var names = {};
  for (item in namesValues) {
    //create new entry in names array with key name
    var name = namesValues[item];
    names[name] = {};                                  //<-- so far, so good

    //cycle through jobs sheet and find all buildings and jobs tied to name
    for(i=1;i<jobsNumRows;i++){

      var jobsName = jobsValues[i][0];
      if(jobsName == name){
        var buildingName = jobsValues[i][2];
        var jobDesc = jobsValues[i][1];           

        //Check if names.name already has a building property
        if(!names.name[buildingName]){
            names.name[buildingName] = []; //<-- doesn't work
        }

         names.name[buildingName].push(jobDesc);  <--probably wouldn't work...?

      }
    }
  } 
}

我该如何设置?我已经查看了有关在对象中创建动态命名属性的所有 SO 问题。这与两次执行此操作略有不同:动态命名属性的动态命名属性。除非当然,这没有什么不同?

谢谢!

4

2 回答 2

2

尝试:

if(!names[name][buildingName]){
    names[name][buildingName] = [];
}

names[name][buildingName].push(jobDesc);

使用 '。' 运算符需要变量的实际值,因此您不能执行以下操作:

var x = "variable";

var obj = {};
obj.x = {};

这意味着obj将有一个名为的属性x,它与先前定义的变量无关。

相反,你应该使用这个:

var obj = {}
obj[x] = {}
于 2014-11-11T17:58:05.503 回答
1

我相信这些行应该是:

    //Check if names.name already has a building property
    if(!names[name][buildingName]){
        names[name][buildingName] = []; //<-- doesn't work
    }

     names[name][buildingName].push(jobDesc);  <--probably wouldn't work...?
于 2014-11-11T17:49:48.217 回答