serializeForm
Serializes a form's data into a plain object.
1/**
2 * Serializes a form's data into a plain object.
3 *
4 * @param form - The HTMLFormElement to serialize.
5 * @returns An object with form field names as keys and their values.
6 */
7export function serializeForm(form: HTMLFormElement): Record<string, any> {
8 const result: Record<string, any> = {};
9 const formData = new FormData(form);
10
11 for (const [key, value] of formData.entries()) {
12 if (result.hasOwnProperty(key)) {
13 result[key] = Array.isArray(result[key])
14 ? [...result[key], value]
15 : [result[key], value];
16 } else {
17 result[key] = value;
18 }
19 }
20
21 return result;
22}
Supports Multiple Values per Field
Automatically aggregates repeated fields (e.g., checkboxes with the same name) into arrays.
Preserves Native Form Semantics
Leverages the
FormData
API, ensuring compatibility with form encoding and browser behaviors.Simple and Declarative Output
Converts complex form structures into a straightforward object representation.
No Dependency on Field Types
Works seamlessly with all input types — text, select, radio, checkbox — without special handling.
Tests | Examples
1function createForm(html: string): HTMLFormElement {
2 const container = document.createElement('div');
3 container.innerHTML = `<form>${html}</form>`;
4 return container.querySelector('form')!;
5}
6
7test('serializeForm - handles single input', () => {
8 const form = createForm('<input name="username" value="john" />');
9 expect(serializeForm(form)).toEqual({ username: 'john' });
10});
11
12test('serializeForm - handles multiple inputs with same name', () => {
13 const form = createForm(`
14 <input name="tags" value="a" />
15 <input name="tags" value="b" />
16 `);
17 expect(serializeForm(form)).toEqual({ tags: ['a', 'b'] });
18});
19
20test('serializeForm - includes selects and checkboxes', () => {
21 const form = createForm(`
22 <select name="color">
23 <option value="red" selected>Red</option>
24 <option value="blue">Blue</option>
25 </select>
26 <input type="checkbox" name="agree" value="yes" checked />
27 `);
28 expect(serializeForm(form)).toEqual({ color: 'red', agree: 'yes' });
29});
30
31test('serializeForm - skips unchecked checkboxes', () => {
32 const form = createForm(`
33 <input type="checkbox" name="foo" value="bar" />
34 `);
35 expect(serializeForm(form)).toEqual({});
36});
Common Use Cases
AJAX Form Submissions
Prepare form data for sending via
fetch
orXMLHttpRequest
in JSON format.Client-Side Validation or Preview
Inspect and validate form values before submitting them to the server.
Storing Form State Locally
Save form progress to
localStorage
orsessionStorage
for later recovery.Integrating with APIs or State Management
Feed serialized form values into Redux actions, React state, or URL query builders.