add formToObject

This commit is contained in:
Nikita
2019-03-13 15:50:06 +03:00
parent db1cbbcb77
commit 5939e3fb27
3 changed files with 30 additions and 8 deletions

25
snippets/formToObject.md Normal file
View File

@ -0,0 +1,25 @@
### formToObject
Serializes a form into an object.
First we transform the `form` into `FormData`, then we convert it into an `array` and from the `array` we collect an `object`
```js
const formToObject = form =>
Array.from(new FormData(form))
.reduce((acc, [key, value]) => ({
...acc,
[key]: value,
}), {})
```
```html
<form id="form">
<input name="email" type="email" />
<input name="name" />
</form>
```
```js
formToObject(document.querySelector('#form')) // { email: 'test@email.com', name: 'Test Name' }
```