Learn how to create queries with or without utilizing URLSearchParams
.
If you're working with typescript, the code snippets are in typescript. If not, simply remove types as it will still function correctly.
Straightforward Approach (Using URLSearchParams)
/**
* Generates query from provided object
* - Does not handle deep nesting
* - Does not eliminate empty fields
* @returns `state1=6&state2=horse` without `?`
*/
function createQuery(queryObject?: Record<string | number, unknown> | null): string {
if (queryObject == null) return ""
const searchParams = new URLSearchParams(queryObject as Record<string, string>)
return searchParams.toString()
}
Problem Solving Approach (Using URLSearchParams)
/**
* Generates query from provided object
* - Does not handle deep nesting
* - Eliminates empty fields
* @returns `state1=6&state2=horse` without `?`
*/
function createQuery(queryObject?: Record<string | number, unknown> | null): string {
if (queryObject == null || !Object.keys(queryObject).length) return ""
for (const key in queryObject) {
if (Object.prototype.hasOwnProperty.call(queryObject, key)) {
const value = queryObject[key]
if (value == null) delete queryObject[key]
}
}
const searchParams = new URLSearchParams(queryObject as Record<string, string>)
return searchParams.toString()
}
Alternative to URLSearchParams
/**
* Generates query from provided object
* - Supports prefixes
* - Supports deep nesting
* - Eliminates empty fields
* @returns `state1=6&state2=horse` without `?`
*/
function createQuery(queryObject?: Record<string | number, unknown> | null, keyPrefix?: string): string {
if (queryObject == null || !Object.keys(queryObject).length) return ""
keyPrefix = keyPrefix ? (keyPrefix + "_") : ""
const queryKeys = Object.keys(queryObject)
const queryArray = queryKeys.map(key => {
const value = queryObject[key]
// additional logic for nested objects can be added here
return keyPrefix + encodeURIComponent(key) + "=" + encodeURIComponent(String(value))
})
return queryArray.filter(Boolean).join("&")
}
Helper Function: isDictionary
The isDictionary
helper function referenced above can be found here
How to Use
Add a ?
at the start of your endpoint followed by createQuery
fetch("/test?" + createQuery({ foo: 12, bar: "@user->here", object: { test: "test", bird: { super: { ultra: { mega: { deep: "human" }, shop: 7 } }, multiple: [1, 2, 3] } } }))
Output
foo=12&bar=%40user-%3Ehere&object_test=test&object_bird_super_ultra_mega_deep=human&object_bird_super_ultra_shop=7&object_bird_multiple=1%2C2%2C3
or
foo: 12
bar: @user->here
object_test: test
object_bird_super_ultra_mega_deep: human
object_bird_super_ultra_shop: 7
object_bird_multiple: 1,2,3
https://i.sstatic.net/p3AKe.png
In Conclusion
Choose from various code snippets based on your specific requirements and objectives.