Yevhen Klymentiev
dark
light
console
darkness
y.klymentiev@gmail.com
Reusable Snippets|Practical utility code for everyday use — custom-built and ready to share

toQueryParams

Converts an object to a URL query string. Supports multiple values per key (e.g., { tag: ['a', 'b'] } => 'tag=a&tag=b').

TypeScript
Copied!
1/**
2 * Converts an object to a URL query string.
3 * Supports multiple values per key (e.g., { tag: ['a', 'b'] } => 'tag=a&tag=b').
4 *
5 * @param params - The input object.
6 * @returns A query string.
7 */
8export function toQueryParams(
9  params: Record<string, string | number | (string | number)[] | undefined | null>
10): string {
11  return Object.entries(params)
12    .flatMap(([key, value]) => {
13      if (value == null) return [];
14      const values = Array.isArray(value) ? value : [value];
15      return values.map(v => `${encodeURIComponent(key)}=${encodeURIComponent(String(v))}`);
16    })
17    .join('&');
18}
  • Array Value Support

    Handles multiple values per key (e.g., tag=a&tag=b) without requiring external libraries.

  • Graceful Handling of Null/Undefined

    Skips null and undefined values, avoiding cluttered or invalid query strings.

  • Safe Encoding

    Uses encodeURIComponent to ensure all keys and values are safely escaped.

  • Compact Output

    Produces a clean and concise query string, making it suitable for URLs and API calls.

Tests | Examples

TypeScript
Copied!
1test('toQueryParams - single key-value pair', () => {
2  expect(toQueryParams({ q: 'search' })).toBe('q=search');
3});
4
5test('toQueryParams - multiple key-value pairs', () => {
6  expect(toQueryParams({ q: 'search', sort: 'asc' })).toBe('q=search&sort=asc');
7});
8
9test('toQueryParams - handles numbers', () => {
10  expect(toQueryParams({ page: 2, limit: 10 })).toBe('page=2&limit=10');
11});
12
13test('toQueryParams - skips null and undefined values', () => {
14  expect(toQueryParams({ q: 'test', skip: undefined, limit: null })).toBe('q=test');
15});
16
17test('toQueryParams - array values create repeated keys', () => {
18  expect(toQueryParams({ tag: ['js', 'ts'] })).toBe('tag=js&tag=ts');
19});
20
21test('toQueryParams - mixed single and array values', () => {
22  expect(toQueryParams({ tag: ['a', 'b'], sort: 'asc' })).toBe('tag=a&tag=b&sort=asc');
23});
24
25test('toQueryParams - encodes special characters', () => {
26  expect(toQueryParams({ q: 'C# & Java' })).toBe('q=C%23%20%26%20Java');
27});

Common Use Cases

  • Constructing API Request URLs

    Convert parameter objects into query strings for fetch or XHR requests.

  • Client-Side Routing or Navigation

    Generate query strings for single-page app navigation (e.g., React Router, Vue Router).

  • State Synchronization with URL

    Reflect application state in the URL to enable deep linking or bookmarking.

  • Search or Filter Forms

    Convert filter values into query parameters for backend or frontend filtering.

Codebase: Utilities -> Network -> toQueryParams | Yevhen Klymentiev