[javascript] How to inspect FormData?

I've tried console.log and looping through it using for in.

Here it the MDN Reference on FormData.

Both attempts are in this fiddle.

var fd = new FormData(),
    key;

// poulate with dummy data
fd.append("key1", "alskdjflasj");
fd.append("key2", "alskdjflasj");

// does not do anything useful
console.log(fd);

// does not do anything useful   
for(key in fd) {
    console.log(key);
}

How can I inspect form data to see what keys have been set.

This question is related to javascript form-data

The answer is


In angular 7 i got entries on console using below line of code.

formData.forEach(entries => console.log(entries));

The MDN suggests the following form:

let formData = new FormData();
formData.append('name', 'Alex Johnson')
for(let keyValuePair of formData.entries()){
    console.log(keyValuePair); //has form ['name','Alex Johnson']
}

Alternatively

for (let [key, value] of formData.entries()) {
 console.log(key, ':', value);
}

Consider adding ES+ Polyfills, in case the browser or environment doesn't support latest JavaScript and FormData API.

I hope this helps.


In certain cases, the use of :

for(var pair of formData.entries(){... 

is impossible.

I've used this code in replacement :

var outputLog = {}, iterator = myFormData.entries(), end = false;
while(end == false) {
   var item = iterator.next();
   if(item.value!=undefined) {
       outputLog[item.value[0]] = item.value[1];
   } else if(item.done==true) {
       end = true;
   }
    }
console.log(outputLog);

It's not a very smart code, but it works...

Hope it's help.


Few short answers

[...fd] // shortest devtool solution
console.log(...fd) // shortest script solution
console.log([...fd]) // Think 2D array makes it more readable
console.table([...fd]) // could use console.table if you like that
console.log(Object.fromEntries(fd)) // Works if all fields are uniq
console.table(Object.fromEntries(fd)) // another representation in table form
new 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)

_x000D_
_x000D_
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))
_x000D_
_x000D_
_x000D_

If you would like to inspect what the raw body would look like then you could use the Response constructor (part of fetch API), this will convert you formdata to what it would actually look like when you upload the formdata

_x000D_
_x000D_
var fd = new FormData()

fd.append('key1', 'value1')
fd.append('key2', 'value2')

new Response(fd).text().then(console.log)
_x000D_
_x000D_
_x000D_


Already answered but if you want to retrieve values in an easy way from a submitted form you can use the spread operator combined with creating a new Map iterable to get a nice structure.

new Map([...new FormData(form)])


Here's a function to log entries of a FormData object to the console as an object.

export const logFormData = (formData) => {
    const entries = formData.entries();
    const result = {};
    let next;
    let pair;
    while ((next = entries.next()) && next.done === false) {
        pair = next.value;
        result[pair[0]] = pair[1];
    }
    console.log(result);
};

MDN doc on .entries()

MDN doc on .next() and .done


  function abc(){ 
    var form = $('#form_name')[0]; 
        var formData = new FormData(form);
        for (var [key, value] of formData.entries()) { 
            console.log(key, value);
        }
        $.ajax({
            type: "POST",
            url: " ",
            data:  formData,
            contentType: false,
            cache: false,
            processData:false,
            beforeSend: function() {

            },
            success: function(data) {


            },

       });
}

ES6+ solutions:

To see the structure of form data:

console.log([...formData])

To see each key-value pair:

for (let [key, value] of formData.entries()) {
  console.log(`${key}: ${value}`);
}

in typeScript of angular 6, this code is working for me.

var formData = new FormData();
formData.append('name', 'value1');
formData.append('name', 'value2');
console.log(formData.get('name')); // this is return first element value.

or for all values:

console.log(formData.getAll('name')); // return all values

Angular

var formData = new FormData();
formData.append('key1', 'value1');
formData.append('key2', 'value2');

formData.forEach((value,key) => {
  console.log(key+" "+value)
});

Not: When I am working on Angular 5 (with TypeScript 2.4.2), I tried as above and it works except a static checking error but also for(var pair of formData.entries()) is not working.

_x000D_
_x000D_
var formData = new FormData();
formData.append('key1', 'value1');
formData.append('key2', 'value2');

formData.forEach((value,key) => {
  console.log(key+" "+value)
});
_x000D_
_x000D_
_x000D_

Check at Stackblitz


I use the formData.entries() method. I'm not sure about all browser support, but it works fine on Firefox.

Taken from https://developer.mozilla.org/en-US/docs/Web/API/FormData/entries

// Create a test FormData object
var formData = new FormData();
formData.append('key1','value1');
formData.append('key2','value2');

// Display the key/value pairs
for (var pair of formData.entries())
{
 console.log(pair[0]+ ', '+ pair[1]); 
}

There is also formData.get() and formData.getAll() with wider browser support, but they only bring up the Values and not the Key. See the link for more info.


You have to understand that FormData::entries() returns an instance of Iterator.

Take this example form:

<form name="test" id="form-id">
    <label for="name">Name</label>
    <input name="name" id="name" type="text">
    <label for="pass">Password</label>
    <input name="pass" id="pass" type="text">
</form>

and this JS-loop:

<script>
    var it = new FormData( document.getElementById('form-id') ).entries();
    var current = {};
    while ( ! current.done ) {
        current = it.next();
        console.info( current )
    }
</script>

Easy Method

I used this code in angular 8

var formData = new FormData();
formData.append('key1', 'value1');
formData.append('key2', 'value2');

 formData.forEach((value,key) => {
    console.log(key+value)
     });


Try this function:

function formDataToObject(formData) {
  return Array.from(formData.entries()).reduce((old, pair) => ({
    ...old,
    [pair[0]]: pair[1],
  }), {});
}