Get form data as an object in browser
Published on: 5/6/2018
A very common scenario for web developers is preventing the default behavior of form submission and getting the data as an Object
to make an API call. But doing that is unexpectedly tricky in Javascript because the submit
event of a form does not include the data.
You can get the data using new FormData(formElement)
but FormData
class has very unintuitive methods, FormData.entries()
was the most usable one I could find. The problem with entries
method is that it returns an iterator
instead of an Object or Array.
Here is a one liner I came-up with to get form data as a Javascript Object
:
const data = Array.from(formElement.elements).filter(el => el.hasAttribute('name')).reduce((prev, curr) => Object.assign(prev, {[curr.name]: curr.files && curr.files.length ? curr.files.item(0) : curr.value}), {})
Here is how to use it in a proper submit
event handler:
const formElement = document.getElementById('myform')
if (formElement) formElement.addEventListener('submit', e => {
e.preventDefault()
const data = Array.from(e.target.elements).filter(el => el.hasAttribute('name')).reduce((prev, curr) => Object.assign(prev, {[curr.name]: curr.files && curr.files.length ? curr.files.item(0) : curr.value}), {})
// make an api call or do whatever you want to with 'data'
})
Cheers!