Files
30-seconds-of-code/snippets/formToObject.md
Angelos Chalaris 611729214a Snippet format update
To match the starter (for the migration)
2019-08-13 10:29:12 +03:00

24 lines
562 B
Markdown

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