Created
June 25, 2020 03:06
-
-
Save Vanlalhriata/4cbae483bb2d995e5bc82dd6ec48b1cc to your computer and use it in GitHub Desktop.
Convert JavaScript object to FormData. Modified from [this answer](https://stackoverflow.com/a/49388446/2530736) on StackOveflow
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
objectToFormData(obj, rootName, ignoreList) { | |
var formData = new FormData(); | |
function appendFormData(data, root) { | |
if (!ignore(root)) { | |
root = root || ''; | |
if (data instanceof File) { | |
formData.append(root, data); | |
} else if (Array.isArray(data)) { | |
for (var i = 0; i < data.length; i++) { | |
appendFormData(data[i], root + '[' + i + ']'); | |
} | |
} else if (typeof data === 'object' && data) { | |
for (var key in data) { | |
if (Object.prototype.hasOwnProperty.call(data, key)) { | |
if (root === '') { | |
appendFormData(data[key], key); | |
} else { | |
appendFormData( | |
data[key], | |
root + '[' + key + ']' | |
); | |
} | |
} | |
} | |
} else { | |
if (typeof data !== 'undefined') { | |
formData.append(root, data ?? ''); | |
} | |
} | |
} | |
} | |
function ignore(root) { | |
return ( | |
Array.isArray(ignoreList) && | |
ignoreList.some(function(x) { | |
return x === root; | |
}) | |
); | |
} | |
appendFormData(obj, rootName); | |
return formData; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment