setValue based on if condition for undefined values

Viewed 177

really struggling with this, any help will be appreciated. I'm very sorry if my formatting is bad, I don't post here much. Please don't ban my question if you aren't happy with the formatting, just tell me what to do next time perhaps.

//Parse the JSON data
var params = JSON.stringify(e.postData.contents);
params = JSON.parse(params);
var myData = JSON.parse(e.postData.contents);
  var firstname = myData.firstname;
  var name = myData.name;
  var surname = myData.surname;
  
//Get the last row without data
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Leads");
var lastRow = Math.max(sheet.getLastRow(),1);
sheet.insertRowAfter(lastRow);
 
//Get current timestamp
var timestamp = new Date();
 
//Insert the data into the sheet
  sheet.getRange(lastRow + 1, 2).setValue(firstname);
  sheet.getRange(lastRow + 1, 3).setValue(surname);

What I'm trying to achieve is in this row

sheet.getRange(lastRow + 1, 2).setValue(firstname);

I would like the value appended to be firstname OR name, in the same row, in the same column. name comes from the var name, just like firstname.

1 Answers

According to your question and your comment, you can check whether name is undefined and then set a value based on that.

Use this:

  if (typeof name == 'undefined'){ 
      sheet.getRange(lastRow + 1, 2).setValue(firstname);
  }
  else {
      sheet.getRange(lastRow + 1, 2).setValue(name);
  }

Instead of this:

sheet.getRange(lastRow + 1, 2).setValue(firstname);
Related