Created
August 31, 2021 10:06
-
-
Save rhietala/c2c5959aa2b89ec3babd6bf000e92688 to your computer and use it in GitHub Desktop.
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
/** | |
* 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