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>
<html>
<body>

<form>
  <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>
</form>

<script>
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 }));
  console.log(options);
/**
[
    {
        "key": "first",
        "value": ""
    },
    {
        "key": "last",
        "value": ""
    },
    {
        "key": "age",
        "value": ""
    }
]
*/
})
</script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Note: this won't work for multi-select

Top comments (0)

18 Useful Github Repositories Every Developer Should Bookmark

18 Useful GitHub repositories every developer should bookmark: everything from learning resources and roadmaps to best practices, system designs, and tools.