It may come as a surprise to some, but FormData
object values cannot directly be displayed / inspected (for example when you use FormData
with console.log
). Luckily, it's not super hard to work around this.
Before we dive into it, for all the examples in this article, let's assume we have the following FormData
object we want to inspect:
const formData = new FormData(); formData.append('name', 'john'); formData.append('langs[]', 'english'); formData.append('langs[]', 'deutsch');
Using the Spread Operator
By simply using the spread operator we can get all of FormData
object elements:
console.log(...formData); // output: // ["name", "john"] // ["langs[]", "english"] // ["langs[]", "deutsch"]
Converting the FormData
Object Into an Array
Using the spread operator we can expand the FormData
object elements into an actual array like so:
console.log([ ...formData ]); /* output: [ ["name", "john"], ["langs[]", "english"], ["langs[]", "deutsch"] ] */
As you can see, the resulting array is an array of arrays containing key/value pairs which may make it more readable as it groups all the values together.
Iterating Through Elements of FormData
Object
Using formData.entries()
with the for...of
loop, we can iterate through the FormData
object elements. For example:
for (const [key, value] of formData.entries()) { console.log(key, value); } // output: // "name", "john" // "langs[]", "english" // "langs[]", "deutsch"
Using the Response
Object
Using the fetch API's Response
object, you can inspect what the raw body would look like when you submit the formData
. For example:
new Response(formData).text().then(console.log); /* output: ------WebKitFormBoundary7qfIBPBQUb04gV4w Content-Disposition: form-data; name="name" john ------WebKitFormBoundary7qfIBPBQUb04gV4w Content-Disposition: form-data; name="langs[]" english ------WebKitFormBoundary7qfIBPBQUb04gV4w Content-Disposition: form-data; name="langs[]" deutsch */
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.