简体   繁体   中英

Google Apps Script: Unable to Access Elements of Returned Object

Problem

Unable to access just the numbers of a returned object. Getting commas and can't seem to stop this behavior.

Current Outcome

    goalList = data[i][3].toString(); -> [2,10,3,4];
    var goal1 = goalList[0]; -> 2
    var goal2 = goalList[2]; -> 1
    var goal3 = goalList[4]; -> ,
    var goal4 = goalList[6]; -> ,

Desired Outcome

    goalList = data[i][3].toString(); -> [2,10,3,4];
var goal1 = goalList[0]; -> 2
var goal2 = goalList[2]; -> 10
var goal3 = goalList[4]; -> 3
var goal4 = goalList[6]; -> 4

Workflow

I have a function that returns the values that are in a spreadsheet. The getReportData() is being passed an array with 4 elements.

var profileList = getIds(processId);

if (profileList.length == 0) {
  processStatus = "Completed";
  ctrlRange.setValues([[processId, processStatus]]);
} else {
  getReportData(profileList, processId);
}
} catch(error) {
 Browser.msgBox(error.message);
 }
}
 function getIds(curPid) {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName('Filtered Views');
  var data = sheet.getDataRange().getValues();

  var profilecmsArray = []

  for (i = 0; i < data.length; i++) {
    var pid = data[i][3];
    if (pid != curPid) {
      profilecmsArray.push([data[i][1], data[i][2], i+1, data[i][4]]);
    }
  }  
  return profilecmsArray;
}

for (i = 0; i < data.length; i++) {
 profileId = data[i][0];
 clientCms = data[i][1];    
 goalList = data[i][3].toString();


 var goal1 = 'ga:goal' + newGoal[0] + 'Completions'
 var goal2 = 'ga:goal' + newGoal[2] + 'Completions'
 var goal3 = 'ga:goal' + newGoal[4] + 'Completions'
 var goal4 = 'ga:goal' + newGoal[6] + 'Completions'

 Logger.log(goal1);
 Logger.log(goal2);
 Logger.log(goal3);
 Logger.log(goal4);

Your code is converting the array to a string instead of converting each element to a separate string. As an array, the first element of [2,10,3,6] would be 2, then 10, then 3, then 6. As a string, the first character of 2,10,3,6 is 2 then , then 1 then 0 then , then 3 then , then 6 .

To correct, try this:

for (i = 0; i < data.length; i++) {
 profileId = data[i][0];
 clientCms = data[i][1];    
 goalList = data[i][3];


 var goal1 = 'ga:goal' + goalList[0].toString() + 'Completions'
 var goal2 = 'ga:goal' + goalList[1].toString() + 'Completions'
 var goal3 = 'ga:goal' + goalList[2].toString() + 'Completions'
 var goal4 = 'ga:goal' + goalList[3].toString() + 'Completions'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM