How to inspect FormData? How to inspect FormData? javascript javascript

How to inspect FormData?


Updated Method:

As of March 2016, recent versions of Chrome and Firefox now support using FormData.entries() to inspect FormData. Source.

// Create a test FormData objectvar formData = new FormData();formData.append('key1', 'value1');formData.append('key2', 'value2');// Display the key/value pairsfor (var pair of formData.entries()) {    console.log(pair[0]+ ', ' + pair[1]); }

Thanks to Ghost Echo and rloth for pointing this out!

Old Answer:

After looking at these Mozilla articles, it looks like there is no way to get data out of a FormData object. You can only use them for building FormData to send via an AJAX request.

I also just found this question that states the same thing: FormData.append("key", "value") is not working.

One way around this would be to build up a regular dictionary and then convert it to FormData:

var myFormData = {    key1: 300,    key2: 'hello world'};var fd = new FormData();for (var key in myFormData) {    console.log(key, myFormData[key]);    fd.append(key, myFormData[key]);}

If you want to debug a plain FormData object, you could also send it in order to examine it in the network request console:

var xhr = new XMLHttpRequest;xhr.open('POST', '/', true);xhr.send(fd);


Few short answers

[...fd] // shortest devtool solutionconsole.log(...fd) // shortest script solutionconsole.log([...fd]) // Think 2D array makes it more readableconsole.table([...fd]) // could use console.table if you like thatconsole.log(Object.fromEntries(fd)) // Works if all fields are uniqconsole.table(Object.fromEntries(fd)) // another representation in table formnew Response(fd).text().then(console.log) // To see the entire raw body

Longer answer

Others suggest logging each entry of entries, but the console.log can also take multiple arguments
console.log(foo, bar)
To take any number of argument you could use the apply method and call it as such: console.log.apply(console, array).
But there is a new ES6 way to apply arguments with spread operator and iterator
console.log(...array).

Knowing this, And the fact that FormData and array's both has a Symbol.iterator method in it's prototype that specifies the default for...of loop, then you can just spread out the arguments with ...iterable without having to go call formData.entries() method (since that is the default function)

var fd = new FormData()fd.append('key1', 'value1')fd.append('key2', 'value2')fd.append('key2', 'value3')// using it's default for...of specified by Symbol.iterator// Same as calling `fd.entries()`for (let [key, value] of fd) {  console.log(`${key}: ${value}`)}// also using it's default for...of specified by Symbol.iterator    console.log(...fd)// Don't work in all browser (use last pair if same key is used more)console.log(Object.fromEntries(fd))