Named Values To Object

Form submit events hand you e.namedValues: each question maps to an array of strings, even for a single answer. namedValuesToObject(namedValues) turns that into a plain object of trimmed strings so confirmation emails and sheet writes do not repeat the same map-and-join code.

When to use

  • onFormSubmit handlers that email the submitter a clean summary
  • Mapping answers into a template or staging row
  • Any script that should not care whether a question was multi-select

How to use this snippet

/** * Turn a form event's namedValues into a simple {question: answer} object. * Arrays are trimmed, blanks dropped, then joined with ", ". * Non-array values are stringified and trimmed. * * @param {Object<string, string[]|string>} namedValues * @return {Object<string, string>} */ function namedValuesToObject(namedValues) { var out = {}; Object.keys(namedValues || {}).forEach(function (key) { var v = namedValues[key]; if (Array.isArray(v)) { out[key] = v .map(function (s) { return String(s == null ? '' : s).trim(); }) .filter(function (s) { return s !== ''; }) .join(', '); } else { out[key] = String(v == null ? '' : v).trim(); } }); return out; }

Example

function onFormSubmit(e) { var answers = namedValuesToObject(e.namedValues); MailApp.sendEmail(answers.Email, 'We got your submission', 'Thanks ' + answers.Name + '. You chose: ' + answers['Which track?']); }

Notes

  • Question titles are the keys, exactly as they appear on the form (including punctuation).
  • Checkbox questions with several picks become one comma-separated string.
  • Empty answers become ''. Missing questions are simply absent from the object.

Happy Coding!

NitroGAS Chrome Extension

Want this snippet handy inside the Apps Script editor? NitroGAS gives you free snippets — plus optional Co-Pilot when you want a boost (Day Pass — $3, or 1-week, 1-month, or yearly passes — no subscription). Happy Coding!

Get the Extension