Files
30-seconds-of-code/snippets/form-to-object.md
Angelos Chalaris 61200d90c4 Kebab file names
2023-04-27 21:58:35 +03:00

29 lines
654 B
Markdown

---
title: Form to object
tags: browser,object
cover: sail-away-2
firstSeen: 2019-03-13T14:50:06+02:00
lastUpdated: 2020-10-19T22:49:51+03:00
---
Encodes a set of form elements as an `object`.
- Use the `FormData` constructor to convert the HTML `form` to `FormData` and `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' }
```