TIDBIT: Array of Key-Value pairs from FormData

Charles Loder - Aug 11 '22 - - Dev Community

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

. . . . . . . . . . . . . . . . . . . . . .