Skip to content

Instantly share code, notes, and snippets.

@srph
Last active February 28, 2018 04:43
Show Gist options
  • Select an option

  • Save srph/8bdfc6e4800ad4bd6ade2aa2820a662b to your computer and use it in GitHub Desktop.

Select an option

Save srph/8bdfc6e4800ad4bd6ade2aa2820a662b to your computer and use it in GitHub Desktop.
JS: Declarative FormData
/**
* Declarative FormData
*
* @usage formdata({ username: '' });
* @param {object} obj
* @return FormData
*/
export default function formdata(obj) {
const form = new FormData();
const flattened = flattenKeys(obj)
Object.keys(flattened).forEach((key) => {
form.append(key, flattened[key]);
})
return form;
}
function flattenKeys(obj, parent = true) {
let output = {}
function flatten(obj, parentKey) {
Object.keys(obj).forEach(key => {
const value = obj[key]
const newKey = parentKey
? `${parentKey}[${key}]`
: key
if ((typeof value === 'object' || Array.isArray(value)) && !(value instanceof File)) {
flatten(value, newKey)
} else {
output[newKey] = value
}
})
}
flatten(obj)
return output
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment