Javascript object to query string

js object to querystring
Difficulty

It can often be useful to transform a javascript object into a query string dynamically, without necessarily knowing the properties of that object. Another good reason is to avoid concatenation for each individual parameter.

This method can be used also in javascript/typescript frameworks like: Angular, React, Svelte, etc.

This is the vanilla javascript version:

/**
 * Convert an object to a query string.
 */
function toQueryString(obj) {
    return o ? ('?' + Object.keys(o).reduce((a, k) => {
      a.push(k + '=' + encodeURIComponent(o[k]));
      return a;
    }, []).join('&')) : '';
}


Typed method (for Typescript/Angular):

  /**
   * Convert an object to a query string.
   */
  public static toQueryString(o: object): string {
    return o ? ('?' + Object.keys(o).reduce((a, k) => {
      a.push(k + '=' + encodeURIComponent(o[k]));
      return a;
    }, []).join('&')) : '';
  }


You can use it simply by chaining the function call to the url string:

window.location.href = 'https://www.google.com' + toQueryString({
          'token1': 'token1',
          'token2': 'token2value',
          'token3': 'tokenValue',
        });

The result will be:

https://www.google.com?token1=token1&token2=token2value&token3=tokenValue


That’s all.
Try it at home!

0
Be the first one to like this.
Please wait...

Leave a Reply

Thanks for choosing to leave a comment.
Please keep in mind that all comments are moderated according to our comment policy, and your email address will NOT be published.
Please do NOT use keywords in the name field. Let's have a personal and meaningful conversation.