← All Exercises

Merge and Serialize URL Query Parameters

intermediatejavascript~15min

Background

Links often carry defaults such as page and sort order while user actions override only a few fields. Building the final query with URLSearchParams avoids broken encoding and unstable parameter order.

Problem

Write mergeQuery(defaults, overrides) that combines two parameter objects, removes keys whose merged value is null or undefined, sorts the remaining keys, repeats array values in order, and returns the query string without a leading question mark.

Input

A JSON object with defaults and overrides; values may be strings, numbers, arrays, null, or undefined-free JSON.

Output

A query string without a leading question mark, using URLSearchParams rules such as plus signs for spaces.

Sample tests

Sample 1

Input: {"defaults":{"page":"1","sort":"new","tags":["js","web"]},"overrides":{"page":2,"tags":["ts"],"q":"hello world","empty":null}}
Expected: page=2&q=hello+world&sort=new&tags=ts

Sample 2

Input: {"defaults":{"q":"js"},"overrides":{"q":null,"lang":"zh"}}
Expected: lang=zh

Sample 3

Input: {"defaults":{},"overrides":{"tag":["a","b"],"note":"a&b=c"}}
Expected: note=a%26b%3Dc&tag=a&tag=b

Your solution

Learning objective

Practice URLSearchParams semantics, stable key ordering, and safe query string construction for browser navigation.