Skip to content

Instantly share code, notes, and snippets.

@stephane-vanraes
Last active May 16, 2022 12:50
Show Gist options
  • Save stephane-vanraes/607001fd5376b4675a5c8a9c9426a753 to your computer and use it in GitHub Desktop.
Save stephane-vanraes/607001fd5376b4675a5c8a9c9426a753 to your computer and use it in GitHub Desktop.
Extracting form data
/*
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), {})
@stephane-vanraes
Copy link
Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment