Last active
July 15, 2020 09:21
-
-
Save Mds92/091828ea857cc556db2ca0f991fee9f6 to your computer and use it in GitHub Desktop.
TypeScript Object to FormData, with support for nested objects, arrays and File objects.
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
static convertModelToFormData(model: any, form: FormData = null, namespace = ''): FormData { | |
let formData = form || new FormData(); | |
for (let propertyName in model) { | |
if (!model.hasOwnProperty(propertyName) || model[propertyName] == undefined) continue; | |
let formKey = namespace ? `${namespace}[${propertyName}]` : propertyName; | |
if (model[propertyName] instanceof Date) { | |
formData.append(formKey, this.dateTimeToString(model[propertyName])); | |
} | |
else if (model[propertyName] instanceof Array) { | |
model[propertyName].forEach((element, index) => { | |
if (typeof element != 'object') | |
formData.append(`${formKey}[]`, element); | |
else { | |
const tempFormKey = `${formKey}[${index}]`; | |
this.convertModelToFormData(element, formData, tempFormKey); | |
} | |
}); | |
} | |
else if (typeof model[propertyName] === 'object' && !(model[propertyName] instanceof File)) { | |
this.convertModelToFormData(model[propertyName], formData, formKey); | |
} | |
else { | |
formData.append(formKey, model[propertyName].toString()); | |
} | |
} | |
return formData; | |
} |
First of all, namespace is a reserved keyword in TypeScript(HandBook and Microsoft/TypeScript@GitHub).
Also, it seems that you forgot to deal with File since the last else will append "[object File]" to the formData
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
if model[propertyName] is 0 or false, then result will not contain this field. I changed the check (!model[propertyName]) for the next function:
like isEmpty(model[propertyName])