HOW TO CONVERT FORMDATA TO JSON OBJECT

Recently, whilst working on a project I needed to take HTML FormData and then convert it to JSON to be sent off to an API. By default the FormData object does not work in the way you would want it to for JSON.

Using thefor..ofsyntax introduced in ECMAScript 2015, we can access the form data entries and iterate over them to get key and value pairs. This will be the verbose solution, scroll to the bottom to get the cleaner solution using.reducebelow.

const formData = new FormData(SomeFormElement).entries();
let jsonObject = {};

for (const [key, value]  of formData) {
    jsonObject[key] = value;
}

By callingentrieson our form data object, it returns the required iterable data we can then access in the form of key and value. In our above example, we actually store each item in an object.

Fortunately, this isn’t a complicated problem to solve. If we had to do this without afor..ofloop, then it wouldn’t be nearly as clean as the above solution is (which can still be improved).

Now, let’s make it more readable by usingreducewhich can work with.entriesto create our object in a slightly cleaner way.

const formData = new FormData(SomeFormElement).entries();

const jsonObject = formData.reduce((acc, [key, val]) => {
  acc[key] = val;
  return acc;
}, {});

Pin It on Pinterest

Share This