Last active
March 20, 2025 03:09
-
-
Save ashaffah/eb82314c2d4ae58ff0e382081430c20a to your computer and use it in GitHub Desktop.
object converter to formData
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
export const objectToFormData = ( | |
obj: Record<string, any>, | |
form?: FormData, | |
namespace?: string, | |
): FormData => { | |
const formData = form || new FormData(); | |
for (const property in obj) { | |
if (obj.hasOwnProperty(property)) { | |
const key = namespace ? `${namespace}[${property}]` : property; | |
const value = obj[property]; | |
if (value instanceof Date) { | |
formData.append(key, value.toISOString()); | |
} else if (value instanceof File || value instanceof Blob) { | |
formData.append(key, value); | |
} else if (typeof value === 'object' && value !== null) { | |
objectToFormData(value, formData, key); | |
} else if (value !== undefined && value !== null) { | |
formData.append(key, value.toString()); | |
} | |
} | |
} | |
return formData; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment