Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Convert object to FormData
function createFormData(object: Object, form?: FormData, namespace?: string): FormData {
const formData = form || new FormData();
for (let property in object) {
if (!object.hasOwnProperty(property) || !object[property]) {
const formKey = namespace ? `${namespace}[${property}]` : property;
if (object[property] instanceof Date) {
formData.append(formKey, object[property].toISOString());
} else if (typeof object[property] === 'object' && !(object[property] instanceof File)) {
createFormData(object[property], formData, formKey);
} else {
formData.append(formKey, object[property]);
return formData;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment