0

I have this script in google script spreadsheet:

function doGet() {
  var response = [];
  var ss = SpreadsheetApp.getActive();
  var thisSheet = ss.getSheetByName('product');
  var lastRow = thisSheet.getLastRow();
  
  var allValues = SpreadsheetApp.getActiveSheet().getDataRange().getValues();
  
  var objectResponse = {};
  
  for(var i = 2; i < lastRow ; ++i){
    
    objectResponse.title = allValues[i][1];
    objectResponse.url = allValues[i][8];
    
    response.push(objectResponse);
  };
   
  return ContentService.createTextOutput(JSON.stringify(response)).setMimeType(ContentService.MimeType.JSON);
}

I make this loop to create an array of objects like this

[
   { title: 'first_title_on2column'  , URL: 'first_url_on9column'},
   { title: 'second_title_on2column'  , URL: 'second_url_on9column'},
   ...
   //until ends <lastRow>
]

but the results is the same on each object. Same 'title' and 'URL'.

How to retrieve each 'title' and 'URL' values?

1 Answer 1

1

your code does not add new object elements to the response array, but only new references to the same object - so all your values are the same

  var objectResponse = {};
  
  for(var i = 2; i < lastRow ; ++i){
    
    objectResponse.title = allValues[i][1];
    objectResponse.url = allValues[i][8];
    
    response.push(objectResponse);
  };

try replacing your code block with a new one and see what happens

  for(var i = 2; i < lastRow ; ++i){
    response.push({title: allValues[i][1], url:allValues[i][8]});
  };

or even like this

allValues.forEach(dataRow => response.push({title: dataRow[1], dataRow[8]}))
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.