DEV Community

Charles Loder
Charles Loder

Posted on


TIDBIT: Array of Key-Value pairs from FormData

I just came across a case where I needed to turn some form data into an array of key value pairs, where the key is the input name.

<!DOCTYPE html>

  <label for="first">First name</label>
  <input type="text" name="first"/>
  <label for="last">Last name</label>
  <input type="text" name="last"/>
  <label for="age">Age</label>
  <input type="number" name="age"/>
  <button type="button" id="btn">Click</button>

document.querySelector("#btn").addEventListener('click', () => {
  const inputs = new FormData(document.querySelector("form"));
  const entries = Object.fromEntries(inputs);
  const options = Object.entries(entries).map(([key, value]) => ({ key, value }));
        "key": "first",
        "value": ""
        "key": "last",
        "value": ""
        "key": "age",
        "value": ""
Enter fullscreen mode Exit fullscreen mode

Note: this won't work for multi-select

Oldest comments (0)

Visualizing Promises and Async/Await 🤯

async await

☝️ Check out this all-time classic DEV post