-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
27 lines (26 loc) · 1.02 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
const OTF = (data: Record<string, any>) => {
const formData = new FormData()
const recurse = (obj: Record<string, any>, prevKey?: string) => {
for (const [key, value] of Object.entries(obj)) {
const newKey = prevKey ? `${prevKey}[${key}]` : key
if (value instanceof File) {
formData.append(newKey, value)
} else if (Array.isArray(value)) {
value.forEach((item, index) => {
if (item instanceof File) {
formData.append(`${newKey}[${index}]`, item)
} else if (typeof item === "object" && item !== null) {
recurse(item, `${newKey}[${index}]`)
}
})
} else if (typeof value === "object" && value !== null) {
recurse(value, newKey)
} else {
formData.append(newKey, value)
}
}
}
recurse(data)
return formData
}
export { OTF }