Use the platform: new FormData(form) collects exactly what the form would submit, and Object.fromEntries(formData) turns it into an object: JSON.stringify(Object.fromEntries(new FormData(form))). Then name the gaps, because that one-liner is where the interview starts. A name can appear several times (a checkbox group, a <select multiple>), and fromEntries keeps only the last value, so use formData.getAll(name) for those. Every value is a string (or a File): numbers and booleans need converting. Unchecked checkboxes aren't in the data at all, and neither are disabled controls or controls without a name. Files can't go into JSON. Finally, names like user[address][city] can be expanded into nested objects, which needs a guard against keys like __proto__.
Read HTML form data and construct a JSON object.
Answer it out loud, in your own words. Then compare.
Interviewers listen for how you get there, not only where you land. The answer opens once you have tried.
FormData does the reading: it walks the form's controls and keeps the name and value of each one that would be submitted. It is iterable as [name, value] pairs, which is what Object.fromEntries takes. Values arrive as strings, so age is '30' and a ticked checkbox with no value attribute is 'on'. The last check shows the gap: three checkboxes named topic leave only the last one.
// FormData collects what the form would submit; fromEntries turns the pairs into an object.function formToObject(form) {return Object.fromEntries(new FormData(form));}function formToJSON(form) {return JSON.stringify(formToObject(form));}
passes 5 checks run on every build, against the native method where there is one
- one value per name becomes an object
- values stay strings, as the form holds them
- an empty form is an empty object
- formToJSON is the JSON text of that object
- the weakness: a repeated name keeps only its last value
For each distinct name, getAll returns every value in form order. More than one value becomes an array. One value is ambiguous: a checkbox group with a single box ticked looks the same as a text field, so a name ending in [] (a common convention) is always treated as a list. An object's keys keep the order in which the names first appear in the form.
// A name can appear more than once (a checkbox group, a multiple select). getAll keeps every// value. A name ending in [] is always a list, even with one value or none ticked but one.function formToObject(form) {const data = new FormData(form);const out = {};for (const key of new Set(data.keys())) {const values = data.getAll(key);if (key.endsWith('[]')) out[key.slice(0, -2)] = values;else out[key] = values.length > 1 ? values : values[0];}return out;}function formToJSON(form) {return JSON.stringify(formToObject(form));}
passes 7 checks run on every build, against the native method where there is one
- one value per name becomes an object
- values stay strings, as the form holds them
- an empty form is an empty object
- formToJSON is the JSON text of that object
- a repeated name becomes a list, in form order
- a name ending in [] is a list even with one value
- keys keep the order of their first appearance
The name is split into keys on dots and brackets, and the object is built along that path; a key made of digits makes its container an array, so items[0].title gives { items: [{ title }] }. Field names are user-controlled input, so two guards matter. Keys __proto__, constructor and prototype are refused: code that walks into them can end up writing to Object.prototype, which changes every object in the program (prototype pollution). And Object.hasOwn is used instead of in, so a field called toString is treated as data, not confused with the inherited method.
// Names as paths: "user.name", "user[address][city]" and "items[0].title" build nested// objects and arrays. Keys that would reach an object's prototype are refused.const UNSAFE = new Set(['__proto__', 'constructor', 'prototype']);function formToObject(form) {const out = {};for (const [name, value] of new FormData(form)) {const list = name.endsWith('[]');const path = (list ? name.slice(0, -2) : name).match(/[^.[\]]+/g) ?? [];if (path.some((key) => UNSAFE.has(key))) continue;let node = out;path.forEach((key, i) => {const own = Object.hasOwn(node, key);if (i < path.length - 1) {// The next key decides the container: digits mean an array.if (!own) node[key] = /^\d+$/.test(path[i + 1]) ? [] : {};node = node[key];} else if (list) {if (!own) node[key] = [];node[key].push(value);} else {node[key] = own ? [].concat(node[key], value) : value; // a repeated name becomes a list}});}return out;}function formToJSON(form) {return JSON.stringify(formToObject(form));}
passes 13 checks run on every build, against the native method where there is one
- one value per name becomes an object
- values stay strings, as the form holds them
- an empty form is an empty object
- formToJSON is the JSON text of that object
- a repeated name becomes a list, in form order
- a name ending in [] is a list even with one value
- keys keep the order of their first appearance
- dots and brackets build nested objects
- a numeric key builds an array
- lists work at any depth
- names that reach the prototype are dropped, and nothing is polluted
- a field named like an inherited method is ordinary data
- a name with no usable key is skipped
What FormData includes
Only successful controls: they need a name, must not be disabled, and checkboxes and radio buttons count only when checked. The submit button is included only if it's passed as the submitter.
Submitting a form with fetch
To send JSON, build the object and JSON.stringify it with a Content-Type: application/json header. To send the form as is, files included, pass the FormData itself as the body and let the browser set the multipart header.
Prototype pollution
Building nested objects from untrusted key paths is a classic way to end up writing to Object.prototype. Refuse the dangerous keys or build on objects with no prototype.
Reading
input.valuefor every element by hand: it includes disabled and unchecked controls that a form would never submit.Object.fromEntrieson a form with checkbox groups or a multiple select: all but the last value are lost.Expecting numbers or booleans: every value is a string until you convert it.
Expecting unchecked checkboxes to appear as
false: they're absent.Putting a
FilethroughJSON.stringify, which gives{}.Expanding names like
a[b][c]without blocking__proto__.
How do you get real numbers and booleans?
The form only has strings, so convert from the control: input.valueAsNumber for type="number", input.checked for a checkbox, valueAsDate for dates. Walk form.elements to know each control's type, or convert against a schema after building the object.
How do you include unchecked checkboxes as false?
They aren't in FormData, so add them yourself: go through form.elements, and for each named checkbox that isn't in the result set it to false.
What about file inputs?
A File isn't JSON. Send the FormData as multipart instead, or upload the file separately and put its id or URL in the JSON.
How would you do it without FormData?
Loop over form.elements, skip controls with no name, disabled ones, unchecked checkboxes and radios, and buttons; for a multiple select take every selected option. That's reimplementing the form data set, which is why FormData is the better answer.
- developer.mozilla.org/en-US/docs/Web/API/FormData/FormData
- developer.mozilla.org/en-US/docs/Web/API/FormData/getAll
- developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/fromEntries
- developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwn
- developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/elements
- developer.mozilla.org/en-US/docs/Web/Security/Attacks/Prototype_pollution