Created
November 10, 2017 19:36
-
-
Save Tagliatti/f42bffc3b27bd9fcd50d6ada7b07f97a to your computer and use it in GitHub Desktop.
object 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
function toFormData(obj, form, namespace) { | |
let fd = form || new FormData(); | |
let formKey; | |
for(let property in obj) { | |
if(obj.hasOwnProperty(property) && obj[property]) { | |
if (namespace) { | |
formKey = namespace + '[' + property + ']'; | |
} else { | |
formKey = property; | |
} | |
// if the property is an object, but not a File, use recursivity. | |
if (obj[property] instanceof Date) { | |
fd.append(formKey, obj[property].toISOString()); | |
} | |
else if (typeof obj[property] === 'object' && !(obj[property] instanceof File)) { | |
toFormData(obj[property], fd, formKey); | |
} else { // if it's a string or a File object | |
fd.append(formKey, obj[property]); | |
} | |
} | |
} | |
return fd; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment