0

I am trying to return the result of a URLFetchApp API fetch in Google App Script back into Google Sheets using 'sheet.getRange().setValues()'. I can populate individual cells from a variable with one value using the 'setValue()' version however I am stuck when trying to populate multiple cells from an array.

If I 'log(arr)' my variable looks like this,
[19-10-12 15:17:45:538 BST] [99]
[19-10-12 15:17:45:669 BST] [98.9]
[19-10-12 15:17:45:829 BST] [91]
[19-10-12 15:17:45:970 BST] [96.4]
[19-10-12 15:17:46:298 BST] [91.6]
[19-10-12 15:17:46:441 BST] [110.6]
[19-10-12 15:17:46:600 BST] [93.7]
[19-10-12 15:17:46:762 BST] [93.8]
[19-10-12 15:17:46:903 BST] [92.6]

I think it should be like this
[99,98.9,91,96.4,91.6,110.6,93.7,93.8,92.6]

There are lots of detailed guides on using the concat() function to merge variables into one array but I cant find any info how to deal with the incorrect way I have it mapped.

The result is the error TypeError: Cannot read property "length" from undefined. which must be due to my improperly formatted array.

Any help greatly appreciated feel like a right potato at the mo.

    var records = results.map(function (positions){

    var position = positions.Metrics.Position;

    var arr = [];

    arr.push(position);

sheet.getRange(6,3,arr.length,arr[0].length).setValues(arr);

    Logger.log(arr)

2
  • It's not clear what you're doing please provide more code and some background of what you're trying to accomplish. Commented Oct 12, 2019 at 16:52
  • Thanks for suggesting a fix to my post. If the answer solved your problem, could you please mark the question as resolved? Commented Oct 13, 2019 at 16:36

1 Answer 1

1

What I see is that you iterate over the results and write to range for every single record. Let's say your position is 99.

var position = positions.Metrics.Position; // === 99
var arr = []; //new empty array
arr.push(position;  // === [99], array with the length of 1.

You then go to 6th row 3rd column and attempt to build a range that spans arr.length rows down (remember, arr.length equals 1) and arr[0].length columns to the right. However, arr[0] equals 99 and the 99 doesn't have a 'length' property (it's undefined!).

sheet.getRange(6,3,arr.length,arr[0].length).setValues(arr);

Here's the code that might solve your problem:

//returns a 2D array where every inner array entry correspons to a row of data
var records = results.map(function(positions){
       return [positions.Metrics.Position];
 });

 sheet.getRange(6,3, records.length, records[0].length).setValues(records);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.