繁体   English   中英

Google Apps脚本批量设置属性

[英]Google Apps Script Bulk Set Properties

另一个GAS问题。 我阅读了有关ScriptProperties和批量设置属性的文档,以及(再次)有关最佳实践的文档。 但是,我对Javascript不熟悉,对GAS还是陌生的,因此,我一直在超出API调用的速率限制。

基本上,我想从电子表格中“获取”所有这些属性,将它们放入数组或对象等中,然后批量设置所有这些属性。 我有正确的键和值,我只是不知道如何将它们临时存储在JS Object或Array或setProperties(Object)方法将接受的某些数据类型中。

这是当前代码(可怕的Sleep定时器是唯一起作用的东西...):

function setSubsequentProperties(propertyRange, sheet) {

  // Get the other Library Properties based on the new Range values.
  // propertyRange is the 2-column 1-row Range for the key/value pairs
  var tableRange = ScriptProperties.getProperty(propertyRange);
  var dataRange = sheet.getRange(tableRange);
  var data = dataRange.getValues();

  // Create a 'properties' Object for bulk-setting to prevent overusing API calls
  //var properties = new Array(data.length);

  // Set a new Script Property for each row
  for (var i = 0; i < data.length; ++i) {
    var row = data[i];
    var propertyKey = row[0];
    var propertyValue = row[1];

    // var myObject = allMyPropertiesInOneObject

    ScriptProperties.setProperty(propertyKey, propertyValue);
    Utilities.sleep(1000);
  }
// setProperties(myObject);
}

我该如何将propertyKeypropertyValue添加到对象以一次全部设置它们? 伪思想在代码块中被注释掉。

既然您说您是Java的新手,那么我假设您也是JSON的新手。 确实有一个ScriptProperties.setProperties()方法,该方法将JSON对象作为参数。

仅修改代码的setProperty()位,这是您可以做的

function setSubsequentProperties(propertyRange, sheet) {

  // Get the other Library Properties based on the new Range values.
  // propertyRange is the 2-column 1-row Range for the key/value pairs
  var tableRange = ScriptProperties.getProperty(propertyRange);
  var dataRange = sheet.getRange(tableRange);
  var data = dataRange.getValues();

  // Create a 'properties' Object for bulk-setting to prevent overusing API calls
  //var properties = new Array(data.length);

  // Set a new Script Property for each row
  var myObject  = {} ;
  for (var i = 0; i < data.length; ++i) {
    var row = data[i];
    var propertyKey = row[0];
    var propertyValue = row[1];

    // var myObject = allMyPropertiesInOneObject
    myObject[propertyKey] = propertyValue; 

  }
  ScriptProperties.setProperties(myObject);
}

为了更新此答案,Google已弃用ScriptProperties,并将其替换为PropertiesService。 您可以使用Properties对象上的setProperties()解决相同的问题,除了必须首先使用对PropertiesService的调用来选择想要的商店类型:

 var myObject = {} ; for (var i = 0; i < data.length; ++i) { var row = data[i]; var propertyKey = row[0]; var propertyValue = row[1]; myObject[propertyKey] = propertyValue; } var myProperties = PropertiesService.getScriptProperties(); // or getUserProperties() or getDocumentProperties() myProperties.setProperties(myObject); 

有关详细信息,请参见文档 注意:这似乎仅适用于简单的键/值对。 当我尝试设置和获取更复杂的JSON对象时,将键设置为值的数组,则可以检索该对象,但不能检索其中的值。 我也无法在其上成功使用JSON.parse()。 如果可以的话,我会再次发布。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM