Skip to content

Instantly share code, notes, and snippets.

@phgrund
Last active October 2, 2020 23:50
Show Gist options
  • Save phgrund/30d02d0037b243be0d5b5023faf9e3d8 to your computer and use it in GitHub Desktop.
Save phgrund/30d02d0037b243be0d5b5023faf9e3d8 to your computer and use it in GitHub Desktop.
Object to form data
/**
* Append every property of an object into a formData, then returns it.
*
* @param {Object} obj Original object.
* @return {FormData} FormData object reference.
*/
function objectToFormData(obj) {
const getPrefix = (prefix, key) => prefix + (prefix ? '[' : '') + key + (prefix ? ']' : '')
const fromArray = (_arr, prefix = '') => {
for(let i = 0; i < _arr.length; i++) {
if(Array.isArray(_arr[i])) {
fromArray(_arr[i], getPrefix(prefix, i))
}
else if(_arr[i] instanceof Object && !(_arr[i] instanceof Blob)) {
fromObject(_arr[i], getPrefix(prefix, i))
} else {
formData.append(getPrefix(prefix, _arr[i]), _arr[i])
}
}
}
const fromObject = (_obj, prefix = '') => {
for(const [key, value] of Object.entries(_obj)) {
if(Array.isArray(value)) {
fromArray(value, getPrefix(prefix, key))
} else if(value instanceof Object && !(value instanceof Blob)) {
fromObject(value, getPrefix(prefix, key))
} else {
formData.append(getPrefix(prefix, key), value)
}
}
}
const formData = new FormData()
fromObject(obj)
return formData
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment