Skip to content

Instantly share code, notes, and snippets.

@fchaussin
Created December 19, 2023 10:36
Show Gist options
  • Save fchaussin/0d18a5a3fc6bb2c798c1a5f31ace1d91 to your computer and use it in GitHub Desktop.
Save fchaussin/0d18a5a3fc6bb2c798c1a5f31ace1d91 to your computer and use it in GitHub Desktop.
Convert JS object to FormData
function objectToFormData(object){
const formData = new FormData();
for (let [key, value] of Object.entries(object)) {
if (Array.isArray(value)) {
value.forEach((item) => {
formData.append(`${key}[]`, item);
});
} else if (typeof value === 'object') {
for (let [subKey, subValue] of Object.entries(value)) {
formData.append(`${key}[${subKey}]`, subValue)
}
} else {
formData.append(key, value);
}
}
return formData;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment