Last active
May 17, 2019 07:10
-
-
Save gucheen/20b2588db3f7a227ab1eca35613ae812 to your computer and use it in GitHub Desktop.
generate query params from object like URLSearchParams()
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
const generateQueryParams = (obj) => { | |
if (typeof obj !== 'object') { | |
return ''; | |
} | |
const strs = []; | |
Object.keys(obj).forEach((key) => { | |
const k = encodeURIComponent(key); | |
const item = obj[key]; | |
if (Array.isArray(item)) { | |
item.forEach((i) => { | |
const v = encodeURIComponent(i); | |
strs.push(`${k}=${v}`); | |
}); | |
} else if (typeof item === 'string' || typeof item === 'number') { | |
const i = encodeURIComponent(item); | |
strs.push(`${k}=${i}`); | |
} | |
}); | |
return strs.join('&'); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The original intention was to solve the form of arrays in search params.
The final array here will be
arr=1&arr=2&arr=3
Conforms to the way most Gateway frameworks parse arrays in search params.