0

Using Google App Script, when I used Logger.log() the for loop iterates properly and I get results for each value. When I try to output this to a google sheet only the last value for each variable is output over and over again for the number of goals.length.

Any help is very much appreciated!

function listGoals() {
      var sheet = SpreadsheetApp.getActiveSheet();
      var filterList = Analytics.Management.Goals.list(accountId, webPropertyId, profileId)
      var goals = filterList.items;
        for (var i = 0, goal; goal = goals[i]; i++) {
            var accountId = goal.accountId;
            var propertyId = goal.webPropertyId;
            var goalNumber = goal.id;
            var goalName = goal.name;

            Logger.log('accountId: ' + accountId);
            Logger.log('profileId: ' + propertyId);
            Logger.log('goal number: ' + goalNumber);
            Logger.log('goal name: ' + goalName);
            //Logger.log prints for each result

            sheet.getRange(1,1,goals.length).setValue(goalNumber);
            sheet.getRange(1,2,goals.length).setValue(goalName);
            //this only prints out the last value of goalNumber and goalName to the sheet

        }
    }

1 Answer 1

1

It doesn't only print the last results, it just keeps overwriting the old result with the new one. goals.length only helps if you then supply an array of arrays containing the values looking as such:

[[1, "Goal 1"], 
 [2, "Goal 2"]]

If you want to print out a list of goalNumber and goalName you need to offset the cell to write in every time. something like

sheet.getRange(1+i,1).setValue(goalNumber);
sheet.getRange(1+i,2).setValue(goalName);

To speed up the process a bit and not do two calls for every goal you can store the id name pairs as arrays within an array and do one final setValues call after the loop finishes executing.

function listGoals() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var filterList = Analytics.Management.Goals.list(accountId, webPropertyId, profileId)
  var goals = filterList.items;
  var goalsToWrite = [];

  for (var i = 0, goal; goal = goals[i]; i++) {
    goalsToWrite.push([goal.id, goal.name]);
  }

  sheet.getRange(1, 1, goals.length, 2).setValues(goalsToWrite);
} 
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much. That's exactly what I wanted. Thanks for also providing the 2nd example with the setValues() as well.

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.