Skip to content

Instantly share code, notes, and snippets.

@earlgreyxxx
Created November 16, 2023 04:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save earlgreyxxx/8c95169213f0a48df0fc8b0ab7278af8 to your computer and use it in GitHub Desktop.
Save earlgreyxxx/8c95169213f0a48df0fc8b0ab7278af8 to your computer and use it in GitHub Desktop.
convert plain object to FormData
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