MCPcopy Create free account
hub / github.com/dailydotdev/apps / formToJson

Function formToJson

packages/shared/src/lib/form.ts:18–72  ·  view source on GitHub ↗
(
  form: HTMLFormElement,
  initialValue?: T,
)

Source from the content-addressed store, hash-verified

16 element instanceof HTMLSelectElement;
17
18export function formToJson<T extends Record<string, unknown>>(
19 form: HTMLFormElement,
20 initialValue?: T,
21): T {
22 const initialData = (initialValue ?? {}) as FormValues;
23
24 const values = Array.from(form.elements).reduce<FormValues>(
25 (acc, element) => {
26 if (!isFormFieldElement(element) || element.name === '') {
27 return acc;
28 }
29
30 // Handle fields that end with [] as arrays.
31 if (element.name.endsWith('[]')) {
32 const fieldName = element.name.slice(0, -2);
33 const existingValue = acc[fieldName];
34 const existingArray = Array.isArray(existingValue) ? existingValue : [];
35
36 if (element.value && element.value.trim().length > 0) {
37 return { ...acc, [fieldName]: [...existingArray, element.value] };
38 }
39
40 return acc;
41 }
42
43 if (element instanceof HTMLInputElement && element.type === 'checkbox') {
44 return { ...acc, [element.name]: element.checked };
45 }
46
47 if (
48 element instanceof HTMLInputElement &&
49 element.type === 'radio' &&
50 !element.checked
51 ) {
52 return acc;
53 }
54
55 if (element instanceof HTMLInputElement && element.type === 'file') {
56 const { files } = element;
57 return {
58 ...acc,
59 [element.name]: !files || files.length === 0 ? null : files,
60 };
61 }
62
63 return {
64 ...acc,
65 [element.name]: element.value.length ? element.value : null,
66 };
67 },
68 initialData,
69 );
70
71 return values as unknown as T;
72}
73
74export const applyZodErrorsToForm = <TFieldValues extends FieldValues>({
75 error: originalError,

Callers 15

onScrapeSubmitFunction · 0.90
onSubmitFeedFunction · 0.90
onSubmitFunction · 0.90
onSubmitFunction · 0.90
onLoginFunction · 0.90
onChangePasswordSubmitFunction · 0.90
onSendEmailFunction · 0.90
handleSubmitFunction · 0.90
handleChangeFunction · 0.90
onSubmitFormFunction · 0.90
handleSubmitFunction · 0.90
onUpdateFunction · 0.90

Calls 1

isFormFieldElementFunction · 0.85

Tested by

no test coverage detected