Created
November 16, 2023 04:27
-
-
Save earlgreyxxx/8c95169213f0a48df0fc8b0ab7278af8 to your computer and use it in GitHub Desktop.
convert plain 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
const getType = o => Object.prototype.toString.call(o).match(/\w+/g)?.at(1); | |
export function plainObjectToFormData(o) | |
{ | |
const isPlainObject = o => 'Object' === getType(o); | |
if(!isPlainObject(o) || Object.keys(o).length > 0) | |
return; | |
const fd = new FormData; | |
Object.entries(o).forEach(v => _value_to(fd, ...v)); | |
return fd; | |
} | |
function _value_to(fd,name,value) | |
{ | |
switch(getType(value)) | |
{ | |
case 'Object': | |
Object.entries(value).forEach(([n,v]) => _value_to(fd,`${name}[${n}]`,v)); | |
break; | |
case 'Array': | |
value.forEach((v,i) => _value_to(fd,`${name}[${i}]`,v)); | |
break; | |
default: | |
fd.append(name,value); | |
break; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment