Last active
October 24, 2017 08:05
-
-
Save riyaz-ali/74ef907e548b436e0c327209c61c27a2 to your computer and use it in GitHub Desktop.
A simple Object-to-querystring serializer
This file contains 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
function isObject(val) { | |
// adapted from https://github.com/jonschlinkert/isobject and https://github.com/jonschlinkert/is-plain-object | |
return(val != null && typeof val === 'object' && Array.isArray(val) === false) === true && | |
Object.prototype.toString.call(val) === '[object Object]'; | |
}; | |
function toQueryString(obj, format) { | |
return Object.keys(obj) | |
.filter(key => (obj[key] != null) || (obj[key] != undefined)) | |
.map(key => { | |
if(Array.isArray(obj[key])) { // for arrays | |
if(format) { // with format | |
return obj[key] | |
.filter(val => (val != null) || (val != undefined)) | |
.map(val => { | |
return `${format.replace(/{(\d+)}/, encodeURIComponent(key))}=${encodeURIComponent(val)}` | |
}) | |
.join('&'); | |
} else { | |
return obj[key] | |
.filter(val => (val != null) || (val != undefined)) | |
.map(val => `${encodeURIComponent(key)}=${encodeURIComponent(val)}`) | |
.join('&'); | |
} | |
} else if(!isObject(obj[key])) { // for plain values | |
if(format) { | |
// if format is specified than format the object key | |
return `${format.replace(/{(\d+)}/, encodeURIComponent(key))}=${encodeURIComponent(obj[key])}` | |
} else { | |
// else just return plain string | |
return `${encodeURIComponent(key)}=${encodeURIComponent(obj[key])}` | |
} | |
} else { // for nested objects, recurse into the object and serialize it | |
if(format) { | |
// if format is specified than create a new format based on previous' | |
return toQueryString(obj[key], `${format.replace(/{(\d+)}/, key)}[{0}]`) | |
} else { | |
return toQueryString(obj[key], `${key}[{0}]`) | |
} | |
} | |
}) | |
.join('&'); | |
} | |
// Some examples | |
// basic | |
toQueryString({a: 1, b: 'string', bool: true, not: false}) | |
// logs a=1&b=string&bool=true¬=false | |
// nested, complex object | |
toQueryString({a: { b: 1, c: { e: 1, f: 2 }, d: [1,2,3] }}); | |
// logs a[b]=1&a[c][e]=1&a[c][f]=2&a[d]=1&a[d]=2&a[d]=3 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment