Created
February 8, 2024 23:41
-
-
Save akullpp/1084ef5b836ce6fb20f5879b2f99545b to your computer and use it in GitHub Desktop.
Repeat query params
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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