All questions

Form Serialize

Premium

Form Serialize

Before you can POST a form as JSON or drop it into state, you have to turn its scattered fields into one object. That sounds trivial until you hit the real rules: unchecked checkboxes vanish, a checkbox group becomes an array, a multi-select yields several values under one name, and names like user[address][city] are meant to build nested structure. This is exactly what jQuery.serializeObject, the qs library, and Rails' form params do.

Implement formSerialize(form) returning a nested object. Lean on FormData, which already knows which controls are "successful". See MDN: FormData.

Signature

function formSerialize(form) {
  // returns a plain (possibly nested) object
}

Examples

// <input name="user[name]" value="Ada">
// <input type="checkbox" name="tags[]" value="a" checked>
// <input type="checkbox" name="tags[]" value="b" checked>
formSerialize(form);
// { user: { name: 'Ada' }, tags: ['a', 'b'] }
// <input type="checkbox" name="agree">        (unchecked)
// <select name="colors" multiple> red*, blue* selected
formSerialize(form);
// { colors: ['red', 'blue'] }   — no `agree` key at all

Notes

  • Successful controls only — unchecked checkboxes/radios and unselected options don't appear. new FormData(form) applies these rules for you.
  • Bracket names build structureuser[addr][city]{ user: { addr: { city } } }; tags[] appends into an array.
  • Repeats become arrays — a multi-select or a checkbox group (same plain name, or name[]) collects multiple values into one array.
  • Values are strings — form control values are always strings; a checked checkbox with no value is 'on'.

Unlock the solution & editor

  • Runnable editor + tests

    Solve in the browser with instant Jest feedback.

  • Detailed solutions

    Walkthroughs, edge cases, and complexity notes.

  • Multi-framework variants

    React, Vue, Vanilla, Angular — same question, different stacks.

Upgrade to Premium