DEV Community

Charles Loder
Charles Loder

Posted on

2 1

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

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay