How to Convert HTML Form Data to JavaScript Object?

In JavaScript, you can convert HTML form values to an object in the following way:

  1. Use the FormData API to access form data;
  2. Store form data (as key/value pairs) in an object — if an element has multiple values, store an array of all the values. Otherwise, store the single value.

For example, suppose you have the following HTML form that has normal <input> fields, a multi-select and some checkboxes with the same name:

<form id="myForm">
  <input type="text" name="name" value="John" />
  <input type="email" name="email" value="[email protected]" />

  <input type="checkbox" name="filters[]" value="hotels" checked /> Hotel
  <input type="checkbox" name="filters[]" value="apartments" checked /> Apartments

  <select name="preference" multiple>
    <option value="single" selected>Single Room</option>
    <option value="double" selected>Double Room</option>
    <option value="king">King Size Room</option>
  </select>

  <button type="submit">Submit</button>
</form>

You can access the submitted data from this HTML form and convert it to an object in the following way:

// ES10+
const form = document.getElementById('myForm');

function formDataToObject(formData) {
  const normalizeValues = (values) => (values.length > 1) ? values : values[0];
  const formElemKeys = Array.from(formData.keys());

  return Object.fromEntries(
    // store array of values or single value for element key
    formElemKeys.map(key => [key, normalizeValues(formData.getAll(key))])
  );
}

form.addEventListener('submit', function (event) {
  event.preventDefault();

  // 1: get form data
  const formData = new FormData(form);
  // 2: store form data in object
  const obj = formDataToObject(formData);

  console.log(obj);
});

This would produce the following result:

/* {
  name: 'John',
  email: '[email protected]',
  filters[]: ['hotels', 'apartments'],
  preference: ['single', 'double']}
*/

The Object.fromEntries() was introduced in ES10. Therefore, to support earlier versions of ES, you could simply loop over the form data instead, for example, by using the FormData.entries() method, like so:

// ES5+
const form = document.getElementById('myForm');

function formDataToObject(formData) {
  const normalizeValues = (values) => (values.length > 1) ? values : values[0];
  const object = {};

  for (const [key, value] of formData.entries()) {
    object[key] = normalizeValues(formData.getAll(key));
  }

  return object;
};

form.addEventListener('submit', function (event) {
  event.preventDefault();

  // 1: get form data
  const formData = new FormData(form);
  // 2: store form data in object
  const jsonObject = formDataToObject(formData);

  console.log(jsonObject);
});

This would produce the same result as in the previous example:

/* {
  name: 'John',
  email: '[email protected]',
  filters[]: ['hotels', 'apartments'],
  preference: ['single', 'double']}
*/

In either of the examples above, the formDataToObject() function processes each form element and returns either a single value or an array of values, depending on whether the element has multiple values or not. This value is then added to its corresponding form element key in the resulting object.


This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.