Javascript对象:动态创建属性和属性名称

时间:2014-11-11 17:45:02

标签: javascript google-apps-script javascript-objects dynamic-properties

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

工作:

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

dataNames:

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

期望的结果:

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

该脚本用于Google的应用脚本,因此无法使用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问题。执行此操作两次略有不同:动态命名属性的动态命名属性。当然,除非这没有什么不同?

非常感谢!

2 个答案:

答案 0 :(得分: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] = {}

答案 1 :(得分: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...?