Skip to content

Instantly share code, notes, and snippets.

@donavon
Last active February 17, 2021 07:29
Show Gist options
  • Save donavon/191af4f054741894bf6db89f0591df24 to your computer and use it in GitHub Desktop.
Save donavon/191af4f054741894bf6db89f0591df24 to your computer and use it in GitHub Desktop.
Here's a good, better, best approach to convert a JavaScript object to "application/x-www-form-urlencoded" postable form data.
const formData = { foo: "foo", bar: "M&Ms" };
// Good 🔥
const postBody = Object.keys(formData)
.map((key) => encodeURIComponent(key) + "=" + encodeURIComponent(body[key]))
.join("&");
// Better 🔥🔥
const postBody = Object.entries(formData)
.map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
.join("&");
// Best 🔥🔥🔥🔥🔥
const postBody = new URLSearchParams(formData).toString();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment