Jens Törnell
Jens Törnell

Reputation: 24748

Javascript formData to array

How do I "convert" formData to an array?

This works well for me but it does not seems to work well in all browsers: https://developer.mozilla.org/en-US/docs/Web/API/FormData/entries

Is there a way to do the same thing with support for older browsers?

var form_data = new FormData(this);
var form_array = [];

for(var pair of formData.entries()) {
   form_array[pair[0]] = pair[1];
}

Update

I tried this without luck:

var entries = form_data.entries();

for (var i = 0; i < entries.length; i++) {
    console.log(entries[i]);
}
console.log(entries);

It gave

Iterator {}

Upvotes: 4

Views: 7143

Answers (4)

R&#250;nar Berg
R&#250;nar Berg

Reputation: 4812

On modern browsers you can use Array.from to get a list of key/value pairs, or Object.fromEntries to transform the FormData into a standard object.

const formData = new FormData();

formData.append("question", "Life, Universe, Everything")
formData.append("answer", 42);
formData.append("isItTrue", false);

// An array of [key, value] pairs.
const pairs = Array.from(formData);

// An object with { key: values }.
const obj = Object.fromEntries(formData);

console.log(pairs);
console.log(obj);

From MDN:

The Array.from() method creates a new, shallow-copied Array instance from an array-like or iterable object.

The Object.fromEntries() static method transforms a list of key-value pairs into an object.

However for legacy browser (without polyfills) you must unpack the iterator manually:

var formData = new FormData(document.forms[0])
var formArray = [];

formData.forEach(function(value) {
  formArray.push(value);
});

console.log(formArray);
<form>
  <input name="foo" value="5">
  <input name="bar" value="42">
</form>

If you want to save the name-value pairs you should iterate over the form instead:

var form = document.forms[0];
var formArray = [];

for (var i = 0; i < form.length; i += 1) {
  formArray.push({ name: form[i].name, value: form[i].value });
}

console.log(formArray);
<form>
  <input name="foo" value="5">
  <input name="bar" value="42">
</form>

Upvotes: 7

David Spector
David Spector

Reputation: 1671

This code generates an object listing the names and values of all the fields in an example form:

var form=document.getElementById(formID);
var pairs={};
for (var i=0; i<form.length ;i++)
    pairs[form[i].name]=form[i].value;
j=JSON.stringify(pairs,null,3);
alert(j);

Upvotes: 0

rho
rho

Reputation: 807

may be

var form_data = new FormData(this);
var array_data = [...form_data]; // ya this works

Upvotes: 0

dvsakgec
dvsakgec

Reputation: 3774

You might want to take a look at this w3shcools example

var x = document.getElementById("frm1");
var text = "";
var i;
for (i = 0; i < x.length ;i++) {
    text += x.elements[i].value + "<br>";
}

Upvotes: 0

Related Questions