Last active
February 28, 2018 04:43
-
-
Save srph/8bdfc6e4800ad4bd6ade2aa2820a662b to your computer and use it in GitHub Desktop.
JS: Declarative FormData
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
| /** | |
| * 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