Iterating Over FormData
What you'll learn: How to loop through all the data stored in a FormData object using built-in iteration methods.
Now that you can read and manipulate FormData, you often need to process all the form fields at once—perhaps to validate everything, log it, or transform the data before sending it. FormData provides several methods to iterate through its contents.
The Iteration Methods
entries() returns an iterator of [key, value] pairs—perfect when you need both the field name and its value:
const formData = new FormData();
formData.append('username', 'alice');
formData.append('email', 'alice@example.com');
for (const [key, value] of formData.entries()) {
console.log(`${key}: ${value}`);
}
// username: alice
// email: alice@example.com
keys() gives you just the field names:
for (const key of formData.keys()) {
console.log(key); // username, email
}
values() provides only the values:
for (const value of formData.values()) {
console.log(value); // alice, alice@example.com
}
forEach() works like array forEach—great for side effects:
formData.forEach((value, key) => {
console.log(`Field ${key} = ${value}`);
});
Think of It Like...
Imagine FormData as a filing cabinet. entries() gives you both the folder label and its contents, keys() just the labels, values() just the contents, and forEach() lets you perform an action on each drawer.
Key Takeaway: Use entries(), keys(), values(), or forEach() to loop through FormData contents, choosing the method that best matches whether you need keys, values, or both.