Are there different Javascript objects in Google App Script?

问题: I had a strange encounter when I was trying to update user data with Google App Script via the Admin SDK Directory Service I wanted to add some values for a customschema li...

问题:

I had a strange encounter when I was trying to update user data with Google App Script via the Admin SDK Directory Service I wanted to add some values for a customschema like this:

 var myCustomschema = {};

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

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

I did not get any error back however the data was never changed in the admin directory. I also tried to JSON.stringify(resource).

Then I tried something like this:

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

And this worked!

So I was wondering why? Is there even a difference between the two approached in the Javascript world? Apparently there is a difference in the Google App Script world.


回答1:

You're missing out the myCustomschema level in your first example.

Your first is:

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

Your second is:

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

Compare:

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;
}

You can fix it with shorthand property notation:

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;
}

Or of course the old way:

resource.customSchemas = { myCustomschema: myCustomschema };
  • 发表于 2020-06-27 19:15
  • 阅读 ( 99 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除