Home > Blockchain >  Why does Object.fromEntries(formData) work
Why does Object.fromEntries(formData) work

Time:12-19

  1. I've got a form.
  2. I listen when user submit it.
  3. I make a new instance of the FormData class.
  <form>
    <input type="text" name="username">
    <input type="submit">
  </form>

  const form = document.querySelector('form');
  form.addEventListener('submit', (e) => {
    e.preventDefault();
    const formData = new FormData(form);
  });

I know that formData.entries() will return an iterable, so i can use a for of loop to get the pairs... What i don't get is why this actually works:

const pairValues = Object.fromEntries(formData);

formData is an instance of a class that HAS multiple methods. Is not an iterable itself.

Does Object.fromEntries looks for an iterator by default?

CodePudding user response:

This is because a FormData object has a Symbol.iterator method, which makes it iterable.

You can check and see that:

formData[Symbol.iterator] === formData.entries

They are the same function.

Now Object.fromEntries(form) accepts an iterable, as also mdn documents:

Parameters

iterable

An iterable such as Array or Map or other objects implementing the iterable protocol.

So Object.fromEntries will invoke formData[Symbol.iterator], which is the same as calling formData.entries.

  • Related