Created
December 19, 2023 10:36
-
-
Save fchaussin/0d18a5a3fc6bb2c798c1a5f31ace1d91 to your computer and use it in GitHub Desktop.
Convert JS object to FormData
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
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