Last active
October 13, 2025 07:49
-
-
Save brainfoolong/c1eb7be6eba82c352e812665d68feaa6 to your computer and use it in GitHub Desktop.
Javascript URLSearchParams <-> JS Object converter (multidimensional)
This file contains hidden or 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
| class BrainsUrlParamsConverter { | |
| /** | |
| * Convert any object to URLSearchParams | |
| * @param {Object} object | |
| * @returns {Object} | |
| */ | |
| static objectToUrlSearchParams (object) { | |
| if (typeof object !== 'object' || !object) { | |
| return | |
| } | |
| function append (object, keyParts) { | |
| for (let key in object) { | |
| let useKeyParts = keyParts | |
| if (!useKeyParts) { | |
| useKeyParts = key | |
| } else { | |
| useKeyParts += '[' + key + ']' | |
| } | |
| const value = object[key] | |
| if (typeof value === 'object' && value) { | |
| append(value, useKeyParts) | |
| } else if (value !== null) { | |
| params.append(useKeyParts, value) | |
| } | |
| } | |
| } | |
| const params = new URLSearchParams() | |
| append(object) | |
| return params | |
| } | |
| /** | |
| * Convert URLSearchParams to multidimensional object | |
| * @param {URLSearchParams} searchParams | |
| * @returns {Object} | |
| */ | |
| static urlSearchParamsToObject (searchParams) { | |
| function append (object, keyParts, value) { | |
| const firstKey = keyParts.shift() | |
| if (keyParts.length === 0) { | |
| object[firstKey] = value | |
| } else { | |
| if (typeof object[firstKey] === 'undefined') { | |
| object[firstKey] = {} | |
| } | |
| append(object[firstKey], keyParts, value) | |
| } | |
| } | |
| const data = {} | |
| for (const searchParam of searchParams.entries()) { | |
| const keyParts = searchParam[0].replace(/\]\[/g, '\/\/').replace(/]$/, '').replace(/\[/g, '\/\/').split('//') | |
| append(data, keyParts, searchParam[1]) | |
| } | |
| return data | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment