Last active
March 18, 2021 04:50
-
-
Save zisan34/f7665446d4972fb8ebf9c010d421f890 to your computer and use it in GitHub Desktop.
This file contains 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
const objectToFormData = function(obj, form = null, namespace = null) { | |
let formDataObj = form || new FormData(); | |
let formKey; | |
for (let property in obj) { | |
// if(obj.hasOwnProperty(property) && obj[property]) | |
if (obj.hasOwnProperty(property) && obj[property] !== null && obj[property] !== undefined) { | |
if (namespace) { | |
formKey = namespace + '[' + property + ']'; | |
} else { | |
formKey = property; | |
} | |
// if the property is an object, but not a File, use recursivity. | |
if (typeof obj[property] === 'object' && !(obj[property] instanceof File)) { | |
if (Object.keys(obj[property]).length === 0) { //if it's an empty object then add the key with empty value. | |
formDataObj.append(formKey, ""); | |
} else { //else use recursivity | |
objectToFormData(obj[property], formDataObj, formKey); | |
} | |
} else if (obj[property] instanceof Date) { | |
formDataObj.append(formKey, obj[property].toISOString()); | |
} else { // if it's a string or a File object | |
formDataObj.append(formKey, obj[property]); | |
} | |
} | |
} | |
return formDataObj; | |
} | |
export default objectToFormData; |
This file contains 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
import objectToFormData from 'objectToFormData'; | |
let test_obj = { | |
a: 'b' | |
}; | |
let formDataObj = objectToFormData(test_obj); | |
axios.post('your url', formDataObj); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment