Search code examples
javascriptgoogle-apps-scriptgoogle-sheetsglobal-variables

Return range as a global variable Google sheets script


I am trying to create a global variable of parsed json data.

I want to use the global variable in other functions

The json parsing works great but I am having no luck with the global variable creation

async function GETELEMENTS(url) {
  var response = await UrlFetchApp.fetch(url);
  var responseText = await response.getContentText();
  var responseJson = JSON.parse(responseText);
  var elementKeys = Object.keys(responseJson.elements[0]);
  
  var data = responseJson.elements.map(e => elementKeys.map(f => {
      return e[f] instanceof Array ? e[f].join('|') : e[f];
  }));
  data.unshift(elementKeys);
  
  if(data.length==0)
   return;
 
  }
  
  var cache = CacheService.getScriptCache();
  cache.put('A', data);
  var cache = CacheService.getPublicCache();

  return data;
}


where cache.get('A') is esseintaly SpreadsheetApp.getActive().getDataRange().getDisplayValues(); of the returned data

Then in a different function, I want to use

myotherfunction(cache.get('A'));

Solution

  • You can declare data outside of every function and it will automatically be a global variable.

    Minimal reproducible example:

    var data;
    
    function GETELEMENTS() {
      data = 'I was defined!';
    }
    
    
    function myotherfunction(){
    
      Logger.log(data); // -> output: null
      GETELEMENTS();
      Logger.log(data); // -> output: I was defined!
    
    }
    

    If you execute myotherfunction, after the line GETELEMENTS() the data will have the value I was defined! defined in GETELEMENTS().