Skip to content

Instantly share code, notes, and snippets.

@shreshthmohan
Created April 8, 2021 15:48
Show Gist options
  • Save shreshthmohan/a5bf255c6350ddc696dab7d3843135f1 to your computer and use it in GitHub Desktop.
Save shreshthmohan/a5bf255c6350ddc696dab7d3843135f1 to your computer and use it in GitHub Desktop.
Object to Query string using URLSearchParams
const paramObj = {
id: '432rqewfda3',
s: 'looking up',
page: 1,
results_per_page: 10,
};
const queryObject = new URLSearchParams(paramObj);
queryObject.toString();
// "id=432rqewfda3&s=looking+up&page=1&results_per_page=10"
// https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams/URLSearchParams#parameters
// The only catch might be that it (constructor URLSearchParams) accepts a "A record of USVString keys and USVString values."
// For 'normal' objects conversion seems to be happening alright.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment