Google 应用脚本中是否有不同的 Javascript 对象?

Are there different Javascript objects in Google App Script?

当我尝试通过 Admin SDK Directory Service 使用 Google App Script 更新用户数据时遇到了奇怪的情况 我想为这样的 customschema 添加一些值:

 var myCustomschema = {};

  myCustomschema.someField = "foo";
  myCustomschema.anotherField = "bar";

  var resource = {};
  resource.customSchemas = myCustomschema;
  var resp = AdminDirectory.Users.patch(resource, user@mydomain.de);

我没有收到任何错误消息,但是管理目录中的数据从未更改过。我也试过 JSON.stringify(resource).

然后我尝试了这样的事情:

var test = {
"customSchemas": {
"myCustomschema": {
  "someField":  "foo",
  "anotherField": "bar"
}
}
 };

这成功了!

所以我想知道为什么?在 Javascript 世界中,两者之间是否存在差异?显然 Google App Script 世界有所不同。

您在第一个示例中漏掉了 myCustomschema 关卡。

你的第一个是:

{
    "customSchemas": {
        "someField": "foo",
        "anotherField": "bar"
    }
}

你的第二个是:

{
    "customSchemas": {
        "myCustomschema": {
            "someField": "foo",
            "anotherField": "bar"
        }
    }
}

比较:

var myCustomschema = {};

myCustomschema.someField = "foo";
myCustomschema.anotherField = "bar";

var resource = {};
resource.customSchemas = myCustomschema;
console.log(JSON.stringify(resource, null, 4));

console.log("vs");

var test = {
      "customSchemas": {
          "myCustomschema": {
              "someField": "foo",
              "anotherField": "bar"
        }
    }
};

console.log(JSON.stringify(test, null, 4));
.as-console-wrapper {
    max-height: 100% !important;
}

你可以用shorthand 属性 表示法修复它:

resource.customSchemas = { myCustomschema };

var myCustomschema = {};

myCustomschema.someField = "foo";
myCustomschema.anotherField = "bar";

var resource = {};
resource.customSchemas = { myCustomschema };
console.log(JSON.stringify(resource, null, 4));

console.log("vs");

var test = {
      "customSchemas": {
          "myCustomschema": {
              "someField": "foo",
              "anotherField": "bar"
        }
    }
};

console.log(JSON.stringify(test, null, 4));
.as-console-wrapper {
    max-height: 100% !important;
}

或者当然是老办法:

resource.customSchemas = { myCustomschema: myCustomschema };