567 B
567 B
title, tags
| title | tags |
|---|---|
| formToObject | browser,object,intermediate |
Encode a set of form elements as an object.
- Use the
FormDataconstructor to convert the HTMLformtoFormData,Array.from()to convert to an array. - Collect the object from the array, using
Array.prototype.reduce().
const formToObject = form =>
Array.from(new FormData(form)).reduce(
(acc, [key, value]) => ({
...acc,
[key]: value
}),
{}
);
formToObject(document.querySelector('#form')); // { email: 'test@email.com', name: 'Test Name' }