30秒学会 JavaScript 片段 · 2019年10月7日

30秒学会 JavaScript 片段 – 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: '[email protected]', name: 'Test Name' }