Skip to content

Instantly share code, notes, and snippets.

@gucheen
Last active May 17, 2019 07:10
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 gucheen/20b2588db3f7a227ab1eca35613ae812 to your computer and use it in GitHub Desktop.
Save gucheen/20b2588db3f7a227ab1eca35613ae812 to your computer and use it in GitHub Desktop.
generate query params from object like URLSearchParams()
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('&');
};
@gucheen
Copy link
Author

gucheen commented May 17, 2019

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment