add serializeForm snippet

This commit is contained in:
Nikita
2019-03-13 15:29:45 +03:00
parent 4f1d5892e8
commit db1cbbcb77
2 changed files with 26 additions and 0 deletions

25
snippets/serializeForm.md Normal file
View File

@ -0,0 +1,25 @@
### serializeForm
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 serializeForm = 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
serializeForm(document.querySelector('#form')) // { email: 'test@email.com', name: 'Test Name' }
```

View File

@ -264,6 +264,7 @@ sampleSize:array,random,intermediate
scrollToTop:browser,intermediate
sdbm:math,utility,intermediate
serializeCookie:utility,string,intermediate
serializeForm:browser,beginner,utility
setStyle:browser,beginner
shallowClone:object,beginner
shank:array,intermediate