Last active
July 17, 2017 15:53
-
-
Save march213/e4759110ea60eb6f2b89924c39dc1770 to your computer and use it in GitHub Desktop.
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
const isObject = value => value === Object(value) | |
const isArray = value => Array.isArray(value) | |
const isFile = value => value instanceof File | |
const makeArrayKey = (key) => { | |
if (key.length > 2 && key.lastIndexOf('[]') === key.length - 2) { | |
return key | |
} else { | |
return key + '[]' | |
} | |
} | |
const objectToFormData = function objectToFormData(obj, fd, pre) { | |
let formData = fd || new FormData() | |
if (obj === undefined || obj === null) { | |
return | |
} | |
Object.keys(obj).forEach(function (prop) { | |
const key = pre ? (pre + '[' + prop + ']') : prop | |
if (isObject(obj[prop]) && !isArray(obj[prop]) && !isFile(obj[prop])) { | |
objectToFormData(obj[prop], formData, key) | |
} else if (isArray(obj[prop])) { | |
obj[prop].forEach(function (value) { | |
const arrayKey = makeArrayKey(key) | |
if (isObject(value) && !isFile(value)) { | |
objectToFormData(value, formData, arrayKey) | |
} else { | |
formData.append(arrayKey, value) | |
} | |
}) | |
} else { | |
formData.append(key, obj[prop]) | |
} | |
}) | |
return formData | |
} | |
export default objectToFormData |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment