Categories: Javascript

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 the for..of syntax 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 .reduce below.

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

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

By calling entries on 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.

Advertisement

Fortunately, this isn’t a complicated problem to solve. If we had to do this without a for..of loop, 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 using reduce which can work with .entries to 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;
}, {});
Advertisement

Recent Posts

Securing phpMyAdmin Like a Pro: Essential Tips and Tricks

Securing phpMyAdmin is crucial to prevent unauthorized access and protect your databases. Here's a guide…

5 months ago

Pasqal raises $100M to build a neutral atom-based quantum computer

Pasqal, a Paris-based quantum computing startup, today announced that it has raised a $100 million…

1 year ago

Apple in talks with Disney, others on VR content for new headset: Report

Developed with Sony Group Corp, the headset will have two ultra-high-resolution displays to handle the…

1 year ago

Microsoft, Amazon results to highlight softening cloud business

After years of blistering growth, most recently fuelled by remote working and studying during the…

1 year ago

Intel chairman Omar Ishrak steps down

Omar Ishrak had stepped down and the chipmaker appointed board director Frank Yeary as his…

1 year ago

Canada to commercialise world's first photonic-based quantum computer

Canadian Prime Minister Justin Trudeau has announced a new federal investment to build and commercialise…

1 year ago