简体   繁体   中英

Google Apps Scripts: Class notation and new Objects

I am trying to create a class to import Google Sheets tables into a more maneuverable. The code:

class SheetData{
  constructor(worksheet, spreadsheet=null) {
    this.spreadsheet = spreadsheet ? spreadsheet : SpreadsheetApp.getActive();
    this.sheet = this.spreadsheet.getSheetByName(worksheet);
    this.values = this.sheet.getDataRange().getValues();
  }
  get records() {
    let cols = this.values[0], temp = {}, out = [];
    for (let row of this.values.slice(1)){
      cols.forEach( (colName,idx) => temp[colName] = row[idx] );
      out.push(temp);
      temp = {};
  }
}

How ever when I try to run it on a sheet Logger.log(new SheetData('Sheet1').values) , I get an Unexpected identifier at the new . What am I doing wrong? I also am not getting any syntax highlighting in the editor, even though I have the V8 runtime enabled.

How about this modification?

Modification points:

  • If you are testing your script in your question, I think that in your script, } is required to be added at the last line ( } is one shortage.).
    • I think that this might be the reason of your issue.
  • And, new SheetData('Sheet1').records is run, undefined is returned. Because no value is returned.

When above points are reflected to your script, it becomes as follows.

Modified script:

class SheetData{
  constructor(worksheet, spreadsheet=null) {
    this.spreadsheet = spreadsheet ? spreadsheet : SpreadsheetApp.getActive();
    this.sheet = this.spreadsheet.getSheetByName(worksheet);
    this.values = this.sheet.getDataRange().getValues();
  }
  get records() {
    let cols = this.values[0], temp = {}, out = [];
    for (let row of this.values.slice(1)){
      cols.forEach( (colName,idx) => temp[colName] = row[idx] );
      out.push(temp);
      temp = {};
    }
    return out; // <--- Added
  }
} // <--- Added

// Please run this function.
function main() {
  var s = new SheetData('Sheet1');
  console.log(s.values);  // or Logger.log(s.values);
  console.log(s.records);  // or Logger.log(s.records);
}

Note:

  • Please confirm whether V8 runtime is enabled again.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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