Skip to content

Instantly share code, notes, and snippets.

@akullpp
Created February 8, 2024 23:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save akullpp/1084ef5b836ce6fb20f5879b2f99545b to your computer and use it in GitHub Desktop.
Save akullpp/1084ef5b836ce6fb20f5879b2f99545b to your computer and use it in GitHub Desktop.
Repeat query params
// Builds the query params in a way that extends arrays of params to be repeated instead of concatenated, e.g.
// { id: 1, foo: ['1', '2', '3'] } => /api?id=1&foo=1&foo=2&foo=3
const repeat = (url: string, params: object) => {
const p = new URLSearchParams()
Object.entries(params).forEach(([key, value]) => {
if (Array.isArray(value)) {
value.forEach((v) => {
return p.append(key, v)
})
} else if (value) {
p.append(key, value)
}
})
const query = `${url}?${p.toString()}`
return query
}
export { repeat }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment