Files
30-seconds-of-code/snippets/formToObject.md
30secondsofcode 2c116fafa7 Travis build: 1100
2019-04-08 05:41:51 +00:00

518 B

formToObject

Encode a set of form elements as an object.

Use the FormData constructor to convert the HTML form to FormData, 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' }