Home > Enterprise >  Google Script is returning the index of the array but I need the value
Google Script is returning the index of the array but I need the value

Time:11-01

I have a google spreadsheet that gets data logged to it via a google form. When the form is logged each time, it triggers a script that gets values from a certain section using:

var tabNumsVal = sheet.getSheetValues(lastRow, tabOneCol.getColumn(), 1, 6)[0];

When I check the array, I can see that the array has the values such as:

0: 12

1: 24

2: 26W

3: 0

4: 0

5: 0

However when I use the following command, it puts the index numbers (0 to 5) into the array instead of the values in the array.

var tabNumsFinal = [];
for (var tabard in tabNumsVal) {
  if (tabard !== "") {
    tabNumsFinal.push(tabard);
  }
}

It used to work but I have had to upgrade my code to Google Script v8 and it seems that this has broken the code. I had to alter the 'for each' code block to a 'for' code block and it seems this is handling the values differently.

I am quite sure this is simple for many people but I really only touch Google Script 1 time each year. I have tried using Logger.log(tabard) to output the data to the execution log, but it just traverses the code and doesn't output anything. I figured this might be because of the !== "" operator, so I placed it above the if statement but still inside the for statement and it still outputs nothing. I tried using Logger.log(tabNumsVal) and Logger.log(tabNumsFinal) and again it output nothing.

To recap: The data from the form is returning correctly into the columns of the spreadsheet, hence it is showing inside the array properly. It's just that the index numbers are being output instead of the values from the array.

CodePudding user response:

Since you're using for in loop, tabard is the index here.

var tabNumsFinal = [];
for (var i in tabNumsVal) {
  let val = tabNumsVal[i];
  if (val !== "") {
    tabNumsFinal.push(val);
  }
}

For in loop

  • Related