Skip to content

Instantly share code, notes, and snippets.

@rhietala
Created August 31, 2021 10:06
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 rhietala/c2c5959aa2b89ec3babd6bf000e92688 to your computer and use it in GitHub Desktop.
Save rhietala/c2c5959aa2b89ec3babd6bf000e92688 to your computer and use it in GitHub Desktop.
/**
* Convert URLSearchParams object to js object
*
* Supports arrays so that if the same key is found more than once,
* convert it to an array.
*
* Removes also `[]` characters from the end of a key and sets that
* key as an array even if there was only one value.
*
* @param u url search params to be converted
* @return js object with the same key-value pairs as u has
*/
export const urlSearchParamsToObj = (
u: URLSearchParams
): Record<string, string | string[]> => {
const ret: Record<string, string | string[]> = {};
u.forEach((value, keyRaw) => {
const keyIsArray = keyRaw.match(/\[\]$/);
const key = keyRaw.replace(/\[\]$/, '');
const current = ret[key];
if (isArray(current)) {
current.push(value);
} else if (keyIsArray) {
ret[key] = [value];
} else if (current != null) {
ret[key] = [current, value];
} else {
ret[key] = value;
}
});
return ret;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment