Search code examples
arraysgoogle-apps-scriptgoogle-forms

Unable to access all ItemResponses in a FormResponse


I have a strange error occurring in an Apps Script function attached to a Google Form.

I call the responses, then list them in an array. The log shows that there are 6 items in the array, which matches the six form questions:

[18-05-08 00:13:31:900 AEST] [ItemResponse, ItemResponse, ItemResponse, ItemResponse, ItemResponse, ItemResponse]

When I call the first two, it works just fine. Any more and it bugs out and says undefined.

// Open a form by ID and log the responses to each question.
var form = FormApp.getActiveForm();
var formResponses = form.getResponses();
for (var i = 0; i < formResponses.length; i++) {
  var formResponse = formResponses[i];
  var editUrl = String(formResponse.getEditResponseUrl());
  var theResponseId = formResponses.indexOf(form);
  var itemResponses = formResponse.getItemResponses();
  var timestamp = formResponse.getTimestamp();  
  var firstName = itemResponses[0].getResponse();
  var lastName = itemResponses[1].getResponse();
  Logger.log(itemResponses); // Log shows there are 6 objects in the array. Matching the amount of Form Questions.

  // If I try to use these variables below, it doesn't work and the script 'breaks' at this point.

  //var number = itemResponses[2].getResponse();
  //var email = itemResponses[3].getResponse();
  //var firstName2 = itemResponses[4].getResponse();
  //var comments = itemResponses[5].getResponse();
}

Note: I have tried FormApp.openById('id'); to see if maybe getting the active form was a problem. This didn't help.


Solution

  • This is because some answers were submitted to a 2 question form. If you submitted some responses prior to updating the form, the answers to these new questions will be "undefined".