How to Make Query Strings From an Object in JavaScript

How to Make Query Strings From an Object in JavaScript

Ferenc Almasi β€’ 2020 August 02 β€’ Read time 2 min read
  • twitter
  • facebook
JavaScript

In JavaScript, you can generate query strings from an object's key-value pairs using a one-liner:

Copied to clipboard! Playground
// Build query strings from object key-value pairs with
// the following line of code:

const params = {
  priceMin: 0,
  priceMax: 100,
  sort: 'asc'
};

Object.keys(params).map(key => `${key}=${params[key]}`).join('&');

// Results in the following output:
"priceMin=0&priceMax=100&sort=asc"
query-string.js

You only need to use Object.keys combined with a map and join. If you also need is a function, just copy the code below:

Copied to clipboard! Playground
const querify = object => Object.keys(object).map(key => `${key}=${object[key]}`).join('&');

querify({
  name: 'Patrick',
  image: '⭐'
});
query-string.js

How Does it Work?

To fully understand how it is working, let's go step by step and pick the function into pieces:

  • First, we pass the object to Object.keys. This will return an array with each key name.
  • Next, we pass it to a map function, that transforms each of the array's element into a string, namely the key of the object equal to its value.
    (${key}=${object[key]}) ➑️ "name=Patrick"
  • Using join, these key-value pairs are joined together using the & sign.
the use of object.keys

Want an Even Shorter Solution?

You can get things done even faster by using the URLSearchParams object:

Copied to clipboard!
new URLSearchParams({  priceMin: 0,  priceMax: 100,  sort: 'asc'}).toString();
urlSearchParams.js

You just need to convert it to a string afterwards.

Looking to improve your skills? Check out our interactive course to master JavaScript from start to finish.
Master JavaScriptinfo Remove ads

Using jQuery

If you are still using jQuery, you can also achieve the same thing by using jQuery.param:

Copied to clipboard!
jQuery.param({  name: 'Patrick',  image: '⭐'});
jquery.js
How to Make Query Strings From an Object in JavaScript
If you would like to see more Webtips, follow @flowforfrank

Resource

  • twitter
  • facebook
JavaScript
Did you find this page helpful?
πŸ“š More Webtips
Frontend Course Dashboard
Master the Art of Frontend
  • check Access 100+ interactive lessons
  • check Unlimited access to hundreds of tutorials
  • check Prepare for technical interviews
Become a Pro

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.