Search code examples
javascriptarraysjsongoogle-apps-scriptgoogle-sheets

How do I use filter with an Apps Script array and fetch only the row with specific user ID in the cell?


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.


Solution

  • 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];
    
    }