Files
30-seconds-of-code/snippets/formToObject.md
Isabelle Viktoria Maciohsek 920a0c390b Update snippet descriptions
2020-10-19 22:49:51 +03:00

570 B

title, tags
title tags
formToObject browser,object,intermediate

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().
const formToObject = form =>
  Array.from(new FormData(form)).reduce(
    (acc, [key, value]) => ({
      ...acc,
      [key]: value
    }),
    {}
  );
formToObject(document.querySelector('#form'));
// { email: 'test@email.com', name: 'Test Name' }