1

I am doing tests on google-sheets and I have this script: What it does is consult data and insert it into the sheet but it does not do so in the desired order.

what I have: bad sheet

what I want: good sheet

function callapi() {


  var response = UrlFetchApp.fetch("https://jsonplaceholder.typicode.com/todos");
  var json = response.getContentText();
  var data = JSON.parse(json);
      for ( var i = 0; i < data.length; i++) {
       var title = data[i].title
        var id = data[i].id
         var userId = data[i].userId
       Logger.log(title)
     var sheet = SpreadsheetApp.getActiveSheet();
  sheet.getRange(sheet.getLastRow() + 1,1).setValue([title]);
    sheet.getRange(sheet.getLastRow() + 1,2).setValue([id]);
     sheet.getRange(sheet.getLastRow() + 1,3).setValue([userId]);
 }
      
  }

I appreciate any help.

1 Answer 1

1

Why?

Because the lastRow changes after each setValue(). If lastrow is 1, after title is set, it becomes 2 > id is set on 2+1 > userId is set on 3+1

Solution:

Use a variable to store the data:

var sheet = SpreadsheetApp.getActiveSheet();
var lr = sheet.getLastRow();
  sheet.getRange(lr + 1,1).setValue([title]);
  sheet.getRange(lr + 1,2).setValue([id]);
  sheet.getRange(lr + 1,3).setValue([userId]);
 }

Simplifying by batching:

var sheet = SpreadsheetApp.getActiveSheet();
var lr = sheet.getLastRow();
sheet.getRange(lr+1,1, 1, 3).setValues([[title, id, userId]]);

Simplifying by batching up further ,

//v8
const data = JSON.parse(json);
const sheet = SpreadsheetApp.getActiveSheet();
const lr = sheet.getLastRow();
const output = data.map(obj=>Object.values(obj));
sheet.getRange(lr + 1, 1, output.length, output[0].length).setValues(output);
}
0

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.