Search code examples
google-apps-scriptgoogle-sheetsmailmerge

0 value doesn't appear using Google Apps Script Simple Mail Merge


During the use of the following script, if in a cell of one the columns that I indicated in the email template, is present "0" as a value, it doesn't appear in the final emails sent.

It is replaced by an empty string as if the cell were empty.

I suppose the issue is in that statement:

// Replace variables from the template with the actual values from the data object.
// If no value is available, replace with the empty string.
for (var i = 0; i < templateVars.length; ++i) {
// normalizeHeader ignores ${"} so we can call it directly here.
var variableData = data[normalizeHeader(templateVars[i])];
email = email.replace(templateVars[i], variableData || "");
}

but if I deleate the boolean symbol and I leave only "variableData" the problem moves on the empty cells (0 value in the sent emails is displayed but the empty cells are returned as "undefined" in the email text).

I hope someone can help me. Thank you


Solution

  • Welcome to JavaScript, where 0, '', "", null, and undefined all mean false-y.

    The issue you have is that the logical OR performed by || uses a non-strict equality comparison, so when variableData is 0 it is type-converted to false (along with the desired conversions of null and undefined) and the alternate substitution of "" is selected.

    To resolve the issue, you will need to perform a more rigorous check of the value of variableData prior to replacing with it.

    For example, a ternary operator can be used:

    var variableData = ...
    variableData = (!variableData && variableData !== 0) ? "" : variableData
    

    This will replace with "" for the other false-y values but allow replacing with the numeric value 0. Also note that String(0) is truthy, so if you return your found variables as a string, the short circuit operator should yield the desired results.