Serialize form data
Turn a form’s fields into an object; repeated names become arrays.
function serialize(form) {
const groups = new Map();
for (const [key, value] of new FormData(form)) groups.set(key, [...(groups.get(key) ?? []), value]);
return Object.fromEntries([...groups].map(([key, values]) => [key, values.length > 1 ? values : values[0]]));
}
Usage
Markup
<form id="signup">
<input name="email" value="[email protected]">
<input name="alias" value=""><input name="alias" value="ana.s">
<input type="checkbox" name="topic" value="product" checked>
<input type="checkbox" name="topic" value="security" checked>
<input type="checkbox" name="topic" value="events">
</form>
Script
serialize(document.querySelector('#signup')); // → { email: '[email protected]', alias: ['', 'ana.s'], topic: ['product', 'security'] }
Know the limits
- The original tested the first value for truthiness, so an empty first value was dropped: alias would have been "ana.s".
- Unchecked checkboxes and disabled fields are not submitted, so they are absent, like the events topic. File inputs produce File objects, which JSON cannot carry; send the FormData itself for uploads.
- Object.fromEntries keeps a field named __proto__ as ordinary data.
The function above is the code the usage lines run. It does not validate its arguments; add checks where it receives untrusted input.
Source & maintenance
Based on Serialize form data from the original 1loc collection by Nguyen Huu Phuoc. Copyright (c) 2020 phuoc-ng. MIT licensed.
Keeps empty first values and __proto__ field names; the original dropped an empty first value. Executed in Chromium. Original MDX retained as inert source evidence.
Maintained by Oveyon. Source commit: 14b481cf60df. Read the license.
Keep exploring
- Check if a given DOMRect is contained within another DOMRect — True when the target lies inside the container or on its edges.
- Check if two DOMRects intersect — Two rects intersect when they meet on both axes.
- Compare two DOMRects for size and position match — Compare x, y, width and height exactly.