Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FormData.delete() doesn't work correctly inside a for loop

Tags:

javascript

var data = new FormData(document.getElementsByTagName("form")[0]);
for(var [key, value] of data.entries()) {
	if (!value) {
    data.delete(key);
    console.log(data.getAll(key));
  }
}
<form>
  <input name="x[1]" type="text" value="">
  <input name="y[2]" type="text" value="">
  <input name="z[3]" type="text" value="">
  <input name="a[4]" type="text" value="">
</form>

I have this form and I get its data using FormData() then I remove the empty values which is all of them but there is always those random not deleted keys even while it is empty

like image 393
Joe Doe Avatar asked Jul 15 '26 04:07

Joe Doe


1 Answers

Even if you remove the if logic and just log the key and delete it, only the first and the third keys are deleted. This is pretty weird. Simultaneously deleting and looping the same collection of keys is probably causing it to behave this way:

var data = new FormData(document.querySelector("form"));

for(var [key, value] of data.entries()) {
    console.log(key); // only 2 keys get logged
    data.delete(key);
}

console.log(Array.from(data.keys())) // still 2 keys are left
<form>
  <input name="x[1]" type="text" value="">
  <input name="y[2]" type="text" value="">
  <input name="z[3]" type="text" value="">
  <input name="a[4]" type="text" value="">
</form>

One fix would be to convert the iterator to an array of entries using Array.from(). Now when the keys are deleted from FormData, the array won't affected:

var data = new FormData(document.querySelector("form"));

for(var [key, value] of Array.from(data.entries())) {
    console.log(key); // every key gets logged now
    data.delete(key);
}

console.log(Array.from(data.keys())) // all are deleted
<form>
  <input name="x[1]" type="text" value="">
  <input name="y[2]" type="text" value="">
  <input name="z[3]" type="text" value="">
  <input name="a[4]" type="text" value="">
</form>
like image 55
adiga Avatar answered Jul 18 '26 15:07

adiga