4 Ways to Convert Object into Query String in Node.js

Last updated on June 1, 2021 Guest Contributor Loading... Post a comment

This article shows you a couple of different ways to convert (stringify) objects into query strings in Node.js.

Using URLSearchParams API

The URLSearchParams class comes with the URL module and is available on the global object so that you can use it without “require” or “import”.

Example:

const params = {
  category: 'book',
  language: 'en',
  page: 12,
  perPage: 10,
  order: 'price',
  orderBy: 'desc',
  author: ['John Doe', 'Jane Dee']
}

const qs = new URLSearchParams(params);
console.log(qs.toString())

Output:

category=book&language=en&page=12&perPage=10&order=price&orderBy=desc&author=John+Doe%2CJane+Dee

Using querystring module

querystring is a built-in module of Node.js that can help us get the job done.

Example:

const queryString = require('querystring');

const obj = {
  name: 'John Doe',
  age: 36, 
  skill: 'Node.js'
}

const qs = queryString.stringify(obj)
console.log(qs)

Output:

name=John%20Doe&age=36&skill=Node.js

The querystring API works fine and is still maintained but it is considered legacy. The official documentation recommends using URLSearchParams instead.

Writing your own function

With a few lines of code, we can write a function to stringify an object.

Example:

const obj2qs = (inputObj) =>
  Object.entries(inputObj)
    .map((i) => [i[0], encodeURIComponent(i[1])].join("="))
    .join("&");

// Try it
const obj = {
  x: 100,
  y: 'yyyyy',
  z: 'ZzZz'
}

const result = obj2qs(obj)
console.log(result)

Output:

x=100&y=yyyyy&z=ZzZz

Using a third-party library

There’re several open-source packages that can easily stringify an object in Node.js. A popular name is querystringify.

Install it by running:

npm install querystringify --save

Example:

const querystringify = require('querystringify');

const obj = {
  foo: 'abc',
  bar: '123'
}

const qs = querystringify.stringify(obj)
console.log(qs);

Output:

foo=abc&bar=123

Conclusion

You’ve learned more than one approach to turn objects into query strings in Node.js. Keep the ball rolling and continue exploring more interesting stuff by taking a look at the following articles:

You can also check out our Node.js category page for the latest tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles