Created
April 30, 2024 23:43
-
-
Save tzkmx/dc7d45f417b933a49daace2dc6da676a to your computer and use it in GitHub Desktop.
Extract from Next.js adapter for tRPC
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* eslint-disable @typescript-eslint/no-non-null-assertion */ | |
function set( | |
obj: Record<string, any>, | |
path: string[] | string, | |
value: unknown, | |
): void { | |
if (typeof path === 'string') { | |
path = path.split(/[\.\[\]]/).filter(Boolean); | |
} | |
if (path.length > 1) { | |
const p = path.shift()!; | |
const isArrayIndex = /^\d+$/.test(path[0]!); | |
obj[p] = obj[p] || (isArrayIndex ? [] : {}); | |
set(obj[p], path, value); | |
return; | |
} | |
const p = path[0]!; | |
if (obj[p] === undefined) { | |
obj[p] = value; | |
} else if (Array.isArray(obj[p])) { | |
obj[p].push(value); | |
} else { | |
obj[p] = [obj[p], value]; | |
} | |
} | |
export function formDataToObject(formData: FormData) { | |
const obj: Record<string, unknown> = {}; | |
for (const [key, value] of formData.entries()) { | |
set(obj, key, value); | |
} | |
return obj; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment