javascriptgoogle-apps-script

TypeError: Cannot set properties of undefined (setting 'FIRST_NAME') in Google Apps Script


To send out language dependent emails from Google Sheets, we have the following:

const EMAIL = [
  {
    LANGUAGE : 'NL',
    HTML_TEMPLATE_FILE : 'MAIL_Invoice_NL',
  },
  {
    LANGUAGE : 'EN',
    HTML_TEMPLATE_FILE : 'MAIL_Invoice_EN',
  }
]

EMAIL.forEach((item)=> {
  item.html = HtmlService.createTemplateFromFile(item.HTML_TEMPLATE_FILE)
})

const customer = {
  language : 'EN'
}

const mail = EMAIL.filter((item) => {
  return item.LANGUAGE == customer.language
})

mail.html.FIRST_NAME = customer.firstname

Throws error:

TypeError: Cannot set properties of undefined (setting 'FIRST_NAME')

Things we've tried:

hardcoding works fine:

const html = HtmlService.createTemplateFromFile(EMAIL[0].HTML_TEMPLATE_FILE)
html.FIRST_NAME = customer.firstname

initializing the variables first fails too:

const EMAIL = [
  {
    LANGUAGE : 'NL',
    HTML_TEMPLATE_FILE : 'MAIL_Invoice_NL',
    html : '',
  },
  {
    LANGUAGE : 'EN',
    HTML_TEMPLATE_FILE : 'MAIL_Invoice_EN',
    html : '',
  }
]

What are we missing here?


Solution

  • Array.filter returns a array and not a single element. Get the first item [0], which has html key:

    mail[0].html.FIRST_NAME = customer.firstname
    

    if not, mail.html would be [filtered array].html, which is undefined and undefined doesn't have FIRST_NAME key and it is a type error to set such a key to undefined.