我正在尝试在所有具有动态属性名称和属性的对象中动态创建对象。这是一个示例:
工作:
| 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 问题。这与两次执行此操作略有不同:动态命名属性的动态命名属性。除非当然,这没有什么不同?
谢谢!