jakub jakub - 1 year ago 79
Javascript Question

Chained method from string

In a script project associated with a Google spreadsheet, I want to write a function that extracts data from a range of cells. There are multiple extraction methods corresponding to different data types, i.e.


The usual way of calling these would be:

var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('mysheet')
var A1 = 'A1:A2'
var values = sheet.getRange(A1).getValues()

However, this happens inside a function, and I want to let the user determine the extraction method in the function call like so:

var r = myfunction(arg1, arg2, extractionMethod = 'getValues')

So I need to be able to use
(i.e. the string that it contains) to call the method.

I tried:

var values = sheet.getRange(A1).window[extractionMethod]

TypeError: Cannot read property "getValues" from undefined. (line 31, file "fun")

I also tried

var values = sheet.getRange(A1)[extractionMethod]

But then
just gives

[16-10-01 04:09:15:014 PDT] function getBackgrounds() {/*

What I want to achieve: A function call that uses the string
(or another valid method name) and is equivalent to calling, for example

var values = sheet.getRange(A1).getValues()

Answer Source

With brackets you can access the properties of an object. If e.g. you define an object like this:

var obj = {
  x: 1,
  m: function() {
    return this.x * 2;

you can get x with obj.x or with obj['x']. obj['m'] will give you the method m and if you want to call m you need to add parentheses i.e. obj.m() or obj['m']().

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download