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.

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;
}, {});

Recent Posts

Unlocking the Secrets of JSON.stringify(): More Than Meets the Eye

JSON (JavaScript Object Notation) is a lightweight data-interchange format widely used in web development. At…

2 months ago

How to Handle AJAX GET/POST Requests in WordPress

AJAX (Asynchronous JavaScript and XML) is a powerful technique used in modern web development that…

3 months ago

Page Speed Optimization: Post-Optimization Dos and Don’ts

Introduction After successfully optimizing your website for speed, it's essential to maintain and build upon…

3 months ago

Ultimate Guide to Securing WordPress Folders: Protect Your Site from Unauthorized Access

Securing your WordPress folders is crucial to safeguarding your website from unauthorized access and potential…

4 months ago

HTML CSS PHP File Upload With Circle Progress Bar

Creating a file upload feature with a circular progress bar involves multiple steps. You'll need…

5 months ago

Using WP Rocket with AWS CloudFront CDN

Integrating WP Rocket with AWS CloudFront CDN helps to optimize and deliver your website content…

5 months ago