Skip to content

Instantly share code, notes, and snippets.

@reks-scripts
Last active April 23, 2018 19:08
Show Gist options
  • Save reks-scripts/a971bc4cd730998d8f40c852f6d541ea to your computer and use it in GitHub Desktop.
Save reks-scripts/a971bc4cd730998d8f40c852f6d541ea to your computer and use it in GitHub Desktop.
objectToQueryString (with lodash): pass in object containing key/value pairs which are converted to URL parameters
const _ = require('lodash');
// any parameters passed with a null value will not be added to the result
const objectToQueryString = obj => {
const results = [];
_.forOwn(obj, (value, key) => {
if (Array.isArray(value)) {
_.forOwn(value, value => {
if (!_.isNil(value))
results.push(`${key}=${value}`);
});
} else {
if (!_.isNil(value))
results.push(`${key}=${value}`);
}
});
return results.join('&');
};
const obj = {
a: 1,
b: 'string',
c: null,
d: [
'array',
'of',
'strings'
]
};
// expected output: a=1&b=string&d=array&d=of&d=strings
console.log(objectToQueryString(obj));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment