Last active
April 23, 2018 19:08
-
-
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
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 _ = 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