Skip to content

Instantly share code, notes, and snippets.

@arronhunt
Created November 27, 2017 03:01
Show Gist options
  • Save arronhunt/35f51a4d6f9f93b714935c80aca43682 to your computer and use it in GitHub Desktop.
Save arronhunt/35f51a4d6f9f93b714935c80aca43682 to your computer and use it in GitHub Desktop.
Javascript keys to query string
export const keysToQueryString = (keys) => (
encodeURI(Object.keys(keys).reduce((string, key, index) => (
`${string}${!index?'?':'&'}${key}=${keys[key]}`
), ''))
);
@arronhunt
Copy link
Author

Example

const query = {
    foo: 'bar',
    fizz: 'buzz',
    count: 20
}

console.log(`https://api.helloworld.com/search${keysToQueryString(query)}`);

// https://api.helloworld.com/search?foo=bar&fizz=buzz&count=20

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