JavaScript

Serialize Form to Object

by @admin
10h ago
Apr 28, 2026
Public
Converts all named form fields into a plain JavaScript object using the FormData API. Handles text inputs, selects, textareas, and checkboxes. Multiple values for the same name (e.g. multi-select, checkboxes) are collected into an array. Ready to JSON.stringify and POST to an API.
JavaScript
function serializeForm(form) {
  const data = {};
  for (const [key, value] of new FormData(form)) {
    if (key in data) {
      data[key] = [].concat(data[key], value);
    } else {
      data[key] = value;
    }
  }
  return data;
}

// Usage
document.querySelector('form').addEventListener('submit', (e) => {
  e.preventDefault();
  const payload = serializeForm(e.target);
  console.log(payload);
  // { name: 'Alice', tags: ['js', 'php'], agree: 'on' }
});
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.