Home > other >  Converting the FormData() to an object
Converting the FormData() to an object

Time:08-07

I have the following code:

const formSubmit = (e) => {
  console.log("form submitted")
  e.preventDefault()
  const formData = new FormData(e.target)
  console.log(formData.get('firstName'))
  console.log(formData.get('lastName'))
}

document.querySelector('form').addEventListener('submit', formSubmit)
<form>
  <input name="firstName" />
  <input name="lastName" />
  <button type="submit"> Create User </button>
</form>

I want to be able to access firstName and lastName as simple as:

console.log(formData.firstName)
console.log(formData.lastName)

However, I can't, because new FormData() returns something (I'm not sure which data type it returns, a map?).

How to convert this retuned value to an object, so I can access its properties as simple as described above?

CodePudding user response:

I found the solution, all you have to do is to use

Object.fromEntries(formData)

ex:

const formSubmit = (e) => {
  console.log("form submitted")
  e.preventDefault()
  const formData = new FormData(e.target)
  console.log(Object.fromEntries(formData))
}

document.querySelector('form').addEventListener('submit', formSubmit)
<form>
  <input name="firstName" />
  <input name="lastName" />
  <button type="submit"> Create User </button>
</form>

CodePudding user response:

so FormData() create new object with methods more about API FormData and here You have more about Date and methods. I hope this helps.

const userForm = document.querySelector('form');

const handleSubmit = (event) => {
    event.preventDefault();
    const userFormData = new FormData(event.target);
    const today = new Date().toLocaleString('en-GB', { timeZone: 'UTC'});
    userFormData.append('date', today);

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

userForm.addEventListener('submit', handleSubmit);
<form method="post" action="">
    <input name="firstName" type="text" placeholder="First name"/>
    <input name="lastName" type="text" placeholder="Last name"/>
    <button typu="submit">Create new User</button>
</form>

  • Related