skip to Main Content

I have an Apps Script which fetches data from four different columns but it fetches all the rows. I’d like it to only push the row that matches the user ID which is a randomly generated 8 digit number.


function doGet(req) {
  var doc = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = doc.getSheetByName('Sheet1');
  var values = sheet.getDataRange().getValues();

  var output = [];
  for(var i = 1; i<values.length; i++) {

    var row = {};
    row['User'] = values[i][0];
    row['Name'] = values[i][1];
    row['Email'] = values[i][2];
    row['Phone'] = values[i][3];
    row['Notes'] = values[i][4];
    

    output.push(row);


  }

return ContentService.createTextOutput(JSON.stringify({data: output})).setMimeType(ContentService.MimeType.JSON); 

}


The result

I’ve tried specifying the cell range like "A1:B1" but it doesnt work.
Tried to specify the 8 digit user ID in the getValues() but no luck.

2

Answers


  1. SUGGESTED SOLUTION

    I recommend adding a condition that would check the user IDs that you have which would be something like this:

    if (row['User'] == "87654321") {
      output.push(row);
    }
    

    The completed code would become:

    function doGet(req) {
      var doc = SpreadsheetApp.getActiveSpreadsheet();
      var sheet = doc.getSheetByName('Sheet1');
      var values = sheet.getDataRange().getValues();
      var output = [];
      for (var i = 1; i < values.length; i++) {
        var row = {};
        row['User'] = values[i][0];
        row['Name'] = values[i][1];
        row['Email'] = values[i][2];
        row['Phone'] = values[i][3];
        row['Notes'] = values[i][4];
        if (row['User'] == "87654321") { // Put the ID of the user here
          output.push(row);
        }
      }
      console.log(JSON.stringify(output));
      return ContentService.createTextOutput(JSON.stringify({ data: output })).setMimeType(ContentService.MimeType.JSON);
    }
    

    OUTPUT

    image

    REFERENCE

    Login or Signup to reply.
  2. Try starting with something like this:

    function myfunk(id) {
      var doc = SpreadsheetApp.getActiveSpreadsheet();
      var sheet = doc.getSheetByName('Sheet1');
      var [User,Name,Email,Phone,Notes] = sheet.getRange(2,1,sheet.getLastRow() - 1,5).getValues().filter(r => r[0]==id)[0];
    
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search