Last active
May 16, 2022 12:50
-
-
Save stephane-vanraes/607001fd5376b4675a5c8a9c9426a753 to your computer and use it in GitHub Desktop.
Extracting form data
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
/* | |
name: 123 | |
name: 456 | |
name2: 'abc' | |
*/ | |
const formData = await request.formData(); | |
// Basic, does not allow multiples, in case of multiples takes last | |
// { name: 456, name2: 'abc' } | |
const data = Object.fromEntries(formData); | |
// Creates an array for each key | |
// { name: [123,456], name2: ['abc'] } | |
const data = [...formData.entries()].reduce((acc, [key, value]) => (acc[key] = [...acc[key] ?? [], value] , acc), {}) | |
// Flattens to a regular prop if the array has length 1 | |
// { name: [123,456], name2: 'abc' } | |
const data = [...formData.entries()].reduce((acc, [key, value]) => (acc.hasOwnProperty(key) ? acc[key] = Array.isArray(acc[key]) ? [...acc[key], value] : [acc[key], value] : acc[key] = value, acc), {}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Counter intuitive, but the thirds approach works faster than the second one.
But this has the side effect that some props are arrays and some are not.
Most use cases will be covered by the first one though (simple basic one) which is a lot faster.