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

Top comments (0)

11 Tips That Make You a Better Typescript Programmer


1 Think in {Set}

Type is an everyday concept to programmers, but it’s surprisingly difficult to define it succinctly. I find it helpful to use Set as a conceptual model instead.

#2 Understand declared type and narrowed type

One extremely powerful typescript feature is automatic type narrowing based on control flow. This means a variable has two types associated with it at any specific point of code location: a declaration type and a narrowed type.

#3 Use discriminated union instead of optional fields


Read the whole post now!