How to create query parameters in Javascript?

186,085

Solution 1

Here you go:

function encodeQueryData(data) {
   const ret = [];
   for (let d in data)
     ret.push(encodeURIComponent(d) + '=' + encodeURIComponent(data[d]));
   return ret.join('&');
}

Usage:

const data = { 'first name': 'George', 'last name': 'Jetson', 'age': 110 };
const querystring = encodeQueryData(data);

Solution 2

URLSearchParams has increasing browser support.

const data = {
  var1: 'value1',
  var2: 'value2'
};

const searchParams = new URLSearchParams(data);

// searchParams.toString() === 'var1=value1&var2=value2'

Node.js offers the querystring module.

const querystring = require('querystring');

const data = {
  var1: 'value1',
  var2: 'value2'
};

const searchParams = querystring.stringify(data);

// searchParams === 'var1=value1&var2=value2'

Solution 3

functional

function encodeData(data) {
    return Object.keys(data).map(function(key) {
        return [key, data[key]].map(encodeURIComponent).join("=");
    }).join("&");
}   

Solution 4

Zabba has provided in a comment on the currently accepted answer a suggestion that to me is the best solution: use jQuery.param().

If I use jQuery.param() on the data in the original question, then the code is simply:

const params = jQuery.param({
    var1: 'value',
    var2: 'value'
});

The variable params will be

"var1=value&var2=value"

For more complicated examples, inputs and outputs, see the jQuery.param() documentation.

Solution 5

ES2017 (ES8)

Making use of Object.entries(), which returns an array of object's [key, value] pairs. For example, for {a: 1, b: 2} it would return [['a', 1], ['b', 2]]. It is not supported (and won't be) only by IE.

Code:

const buildURLQuery = obj =>
      Object.entries(obj)
            .map(pair => pair.map(encodeURIComponent).join('='))
            .join('&');

Example:

buildURLQuery({name: 'John', gender: 'male'});

Result:

"name=John&gender=male"
Share:
186,085

Related videos on Youtube

cnu
Author by

cnu

A computer programmer, recently became an entrepreneur ready to make my own dent.

Updated on February 02, 2022

Comments

  • cnu
    cnu over 2 years

    Is there any way to create the query parameters for doing a GET request in JavaScript?

    Just like in Python you have urllib.urlencode(), which takes in a dictionary (or list of two tuples) and creates a string like 'var1=value1&var2=value2'.

  • troelskn
    troelskn over 15 years
    When iterating with for, use hasOwnProperty to ensure interoperability.
  • AnthonyWJones
    AnthonyWJones over 15 years
    encodeURIComponent handles this and doesn't incorrectly use + for a space.
  • Shog9
    Shog9 over 15 years
    @troelskn, good point... although in this case, someone would have to be extending Object.prototype to break it, which is a pretty bad idea to start with.
  • Cesar Canassa
    Cesar Canassa over 12 years
    @Shog9 Why is it a bad ideia?
  • Shog9
    Shog9 over 12 years
  • Akseli Palén
    Akseli Palén over 11 years
    Nice one! .map() has been implemented in JavaScript 1.6 so almost all browsers, even the granny ones support it. But as you can guess IE does not except IE 9+. But do not worry, there is a workaround. Source: developer.mozilla.org/en-US/docs/JavaScript/Reference/…
  • Tim
    Tim almost 9 years
    jQuery.param() takes object and transform it to GET query string (this function better matches the question).
  • dylanh724
    dylanh724 over 6 years
    var data = { bloop1: true, bloop2: "something" }; var url = "https://something.com/?"; var params = encodeData(data); var finalUrl = url + params; // Is this the right use? Should produce https://www.something.com/?bloop1=true&bloop2=something ?
  • eaorak
    eaorak about 6 years
    I've later realized that it's actually a slightly different version of @manav's response below. But anyway, it could still be preferable for ES6 syntax.
  • Przemek
    Przemek almost 6 years
    First of all, you are not encoding the keys. Also, you should use encodeURIComponent() instead of encodeURI. Read about the difference.
  • Przemek
    Przemek almost 6 years
    @DylanHunt: Yup…
  • kano
    kano over 4 years
    Definitely the clean and modern approach. You can also later freely call searchParams.append(otherData)
  • masterxilo
    masterxilo about 4 years
    Downvote because I have no idea whether this solution acts according to the specification and will always work. Prefer the standard URLSearchParams that is now available. OP please consider retreating this outdated answer.
  • masterxilo
    masterxilo about 4 years
    Very unspecific answer.
  • wrkwrk
    wrkwrk over 3 years
    URLSearchParams will parse White space as '+' instead of '%20'. For example, new URLSearchParams({ abc: 'a b c' }).toString()result in 'abc=a+b+c'
  • hanshenrik
    hanshenrik over 3 years
    this is insufficient. encodeQueryData({foo:{bar:123}}) returns foo=%5Bobject%20Object%5D , but the correct return value would be foo%5Bbar%5D=123
  • hanshenrik
    hanshenrik over 3 years
    this is insufficient. encodeData({foo:{bar:123}}) returns foo=%5Bobject%20Object%5D , but the correct return value would be foo%5Bbar%5D=123
  • hanshenrik
    hanshenrik over 3 years
    this is an improvement, yes, but it's still insufficient: encodeQueryData({foo:{bar:123}}) returns foo[]=123 , but the correct return value would be foo%5Bbar%5D=123
  • francistheturd
    francistheturd over 2 years
    How is it that in 2021 there is not a more standardized way of achieving this? For example, what about adding ? only when searchParams are not blank.
  • LP Square
    LP Square about 2 years
    This is the new correct way. function encodeQueryData(data) { return new URLSearchParams(data).toString(); }