DEV Community

Jérôme Pott
Jérôme Pott

Posted on

jQuery.param() in Vanilla JavaScript

Let's imagine we want to make a GET request to the Google Translate REST endpoint https://translation.googleapis.com/language/translate/v2.

We need to pass the source & target languages, the text to translate, the format and our API key.


const params = {
                  key: 'XXX',
                  q: 'I like coding',
                  target: 'fr',
                  source: 'en',
                  format: 'text'
                }

Enter fullscreen mode Exit fullscreen mode

Our GET request URL should look like that:
https://translation.googleapis.com/language/translate/v2?key=XXX&q=I+like+coding&target=fr&source=en&format=text

To obtain that URL, we need to serialize the params object. Using jQuery, we can simply write jQuery.param(params).

In plain JavaScript, we can use the URLSearchParams constructor, which returns a URLSearchParams object.

The problem is that URLSearchParams is quite restrictive about what formats it accepts. For instance, we can't just pass it our params object. It needs to be in this format:

[ ["key","XXX"], ["q","I like coding"], ["target","fr"], ["source","en"],["format","text"] ]

Worry not, EcmaScript 2017 gave us the Object.entries method, which turns our object in the exact format we need:

Object.entries(params) // [ ["key","XXX"], ["q","I like coding"], ["target","fr"], ["source","en"], ["format","text"] ]
Enter fullscreen mode Exit fullscreen mode

We can then initialize our URLSearchParams object in this way:

const URLparams = new URLSearchParams(Object.entries(params))
urlParams.toString() // "key=XXX&q=I+like+coding&target=fr&source=en&format=text"
Enter fullscreen mode Exit fullscreen mode

Finally we can make our request. Note that you can directly append the URLparams object to the URL string without calling the toString() method. But don't forget to add the ? character before it.

fetch('https://translation.googleapis.com/language/translate/v2?' + URLparams)
Enter fullscreen mode Exit fullscreen mode

That's it! Thank you for reading my post and let me know in the comment section below if you know of better/other ways to achieve this.

Note on browser support

Object.entries and URLSearchParams are supported in all modern browsers and can be polyfilled in IE11: Object.entries polyfill, URLSearchParams polyfill

Top comments (3)

Collapse
 
mornir profile image
Jérôme Pott

Yes, you are right. I've added a note about browser support to my post.

Collapse
 
codevault profile image
Sergiu Mureşan

I am way behind on JS news and this caught me by surprise. Didn't know of both entries and URLSearchParams. Thanks for posting!

Collapse
 
mornir profile image
Jérôme Pott

Thank you for your comment! It really motivates me to post more 😃