Skip to content

Instantly share code, notes, and snippets.

@abdelfattahradwan
Created April 17, 2024 00:35
Show Gist options
  • Save abdelfattahradwan/2657b0c91f4cddb0c374aeda48128e1b to your computer and use it in GitHub Desktop.
Save abdelfattahradwan/2657b0c91f4cddb0c374aeda48128e1b to your computer and use it in GitHub Desktop.
A function to convert FormData into an object, supporting multiple values per key using arrays.
export default async function formDataToObject(
formData: Promise<FormData> | FormData,
): Promise<Record<string, unknown>> {
const object: Record<string, unknown> = {};
for (const [key, value] of await Promise.resolve(formData)) {
const property = object[key];
if (property === undefined) {
object[key] = value;
} else if (Array.isArray(property)) {
property.push(value);
} else {
object[key] = [property, value];
}
}
return object;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment