Reputation: 56
I am trying to destructure a 2D array in Google Apps Script and it remains unchanged.
I found a link that explains how to destructure an array in google apps script similar to the syntax for javascript es6.
The link is https://plus.google.com/u/0/+DimuDesigns/posts/9FDJx2qe4gZ
The example they give works fine for me in as a separate function.
function readData() {
var id = '1P4aVeFJMT9e0ijoFt262IuLlnjHte8hl2iUeU_kk-AQ'; //ID of the
projects spreadsheet
var ass = SpreadsheetApp.openById(id); //Initilize spreadsheet
var sheet = ass.getSheetByName('Sheet1'); //Get sheet instence
var row1data = sheet.getRange('A1:F1').getValues();
[a1, b1, c1, d1, e1, f1] = [row1data];
//DEBUG
Logger.log(a1);
}
expected output to log should be the data in cell A1 which is the first item in the array.
actual output is the array itself.
I am a beginner in general so a clear explanation with well commented code would be appreciated.
Upvotes: 3
Views: 410
Reputation: 201358
How about this modification? I think that there are 2 errors in your script.
When the values of "a1","b1","c1","d1","e1" and "f1" are put in the cells of "A1:F1", row1data
retrieved by var row1data = sheet.getRange('A1:F1').getValues()
is like [["a1","b1","c1","d1","e1","f1"]]
. This is 2 dimensional array.
Variables of a1, b1, c1, d1, e1, f1
of [a1, b1, c1, d1, e1, f1]
are required to be declared.
When above points are reflected to your script, it becomes as follows.
Please modify as follows.
From:[a1, b1, c1, d1, e1, f1] = [row1data];
//DEBUG
Logger.log(a1);
To:
var a1, b1, c1, d1, e1, f1;
[a1, b1, c1, d1, e1, f1] = row1data[0];
//DEBUG
Logger.log(a1);
[[a1, b1, c1, d1, e1, f1]] = row1data
instead of [a1, b1, c1, d1, e1, f1] = row1data[0]
.[row1data]
in your script is used, it becomes [[[a1, b1, c1, d1, e1, f1]]] = [row1data]
.Upvotes: 3