Convert Javascript Object to a URL Query String – Convert it

js object to querystring
Difficulty

Creating dynamic URL query strings from a JavaScript object is a common task for developers. This is especially useful when making API requests, redirecting users with specific parameters, or building complex search functionality. This article will show you a clean and efficient way to convert a JavaScript object into a URL-friendly query string, without manual string concatenation.


Why Convert an Object to a Query String?

Manually building a query string can be tedious and prone to errors. Imagine you have a set of user preferences or API filters in an object. You could concatenate them like this:

const user = { name: 'John Doe', city: 'New York' };
const url = `https://example.com/search?name=${user.name}&city=${user.city}`;

This approach quickly becomes unmanageable as the number of parameters grows. A more robust solution is to programmatically generate the query string from the object’s properties, which also handles URL encoding for special characters.


The Modern JavaScript Solution

The most efficient way to convert an object to a query string in modern JavaScript involves using Object.entries() and URLSearchParams(). This method is concise, readable, and handles URL encoding automatically.

Using URLSearchParams

The URLSearchParams interface provides a simple way to work with the query string of a URL. You can initialize it with an object, and it will handle the conversion and encoding for you.

/**
 * Convert an object to a query string.
 * @param {object} obj
 * @returns {string}
 */
const toQueryString = (obj) => {
  if (!obj) {
    return '';
  }
  const params = new URLSearchParams(obj);
  return `?${params.toString()}`;
};

// Example Usage:
const data = {
  name: 'John Doe',
  city: 'New York',
  'search-term': 'javascript objects',
};

const queryString = toQueryString(data);
console.log(queryString); 
// Output: ?name=John+Doe&city=New+York&search-term=javascript+objects

// Use it with a URL
const finalUrl = `https://example.com/results${queryString}`;
console.log(finalUrl);
// Output: https://example.com/results?name=John+Doe&city=New+York&search-term=javascript+objects

This method is the recommended approach for its simplicity and built-in features.

An alternative version

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('&')) : '';
  }

The “Vanilla” JavaScript Approach

If you need a solution for older environments or prefer not to use URLSearchParams, you can use the Object.keys() method combined with reduce() and encodeURIComponent().

/**
 * Convert an object to a query string.
 * @param {object} obj
 * @returns {string}
 */
const toQueryStringOld = (obj) => {
  if (!obj) {
    return '';
  }
  const keys = Object.keys(obj);
  if (keys.length === 0) {
    return '';
  }

  const queryString = keys
    .reduce((accumulator, key) => {
      // Ensure the value is properly URL encoded
      accumulator.push(`${key}=${encodeURIComponent(obj[key])}`);
      return accumulator;
    }, [])
    .join('&');

  return `?${queryString}`;
};

TypeScript / Angular Version

For a TypeScript-friendly version, you can define a static method within a class or a simple function with type annotations.

/**
 * Convert an object to a query string.
 * @param {object} obj
 * @returns {string}
 */
export const toQueryStringTyped = (obj: object): string => {
  if (!obj || Object.keys(obj).length === 0) {
    return '';
  }
  const params = new URLSearchParams(obj as any);
  return `?${params.toString()}`;
};

The URLSearchParams method is still the cleanest choice, even in TypeScript. The as any type assertion is necessary because URLSearchParams expects a Record<string, string>, but it will still handle a general object type correctly.


Putting It All Together

Here’s how you might use these functions to construct a URL and perform a redirect:

const filterOptions = {
  category: 'books',
  sort: 'price_desc',
  page: 1,
};

// Assuming you are using the modern `toQueryString` function
const finalUrl = `https://myshop.com/products${toQueryString(filterOptions)}`;

// Redirect the user
window.location.href = finalUrl;
// The URL will become: https://myshop.com/products?category=books&sort=price_desc&page=1

Using these methods ensures that your code remains dynamic, clean, and easily maintainable, regardless of the number of parameters you need to include in your query strings

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.

BlogoBay
Privacy Overview

This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.