Introduction
In this lab, we will explore how to convert a set of form elements into an object using JavaScript. We will make use of the FormData constructor and the Array.from() method to create an array of form data. We will then use the Array.prototype.reduce() method to collect the form data into an object. By the end of this lab, you will have a better understanding of how to collect and organize form data using JavaScript.
Converting a Form to an Object
To practice coding, open the Terminal/SSH and type node. You can encode a set of form elements as an object using the following steps:
- Use the
FormDataconstructor to convert the HTMLformtoFormData. - Convert the
FormDatato an array usingArray.from(). - Collect the object from the array using
Array.prototype.reduce().
Here's an example code snippet:
const formToObject = (form) =>
Array.from(new FormData(form)).reduce(
(acc, [key, value]) => ({
...acc,
[key]: value
}),
{}
);
To convert a specific form, you can call the formToObject function and pass in the form element as an argument:
formToObject(document.querySelector("#form"));
// { email: 'test@email.com', name: 'Test Name' }
Summary
Congratulations! You have completed the Form to Object lab. You can practice more labs in LabEx to improve your skills.