Last active
February 17, 2021 07:29
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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