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 β€’ πŸ“– 2 min read

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

// 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
Copied to clipboard!

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:

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

querify({
  name: 'Patrick',
  image: '⭐'
});
query-string.js
Copied to clipboard!
Looking to improve your skills? Check out our interactive course to master JavaScript from start to finish.
Master JavaScript

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:

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

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 JavaScript

Using jQuery

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

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

Resource

Did you find this page helpful?
πŸ“š More Webtips
Frontend Course Dashboard
Master the Art of Frontend
  • check Access exclusive interactive lessons
  • check Unlimited access to hundreds of tutorials
  • check Remove ads to learn without distractions
Become a Pro

Recommended