Created
June 10, 2016 05:14
-
-
Save seoh/f3d7d7030e224f07dbfff579db68d559 to your computer and use it in GitHub Desktop.
JSON to QueryString
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 prefixes = (prev, next) => prev ? `${prev}[${next}]` : next | |
const serialize = (key, value, prefix = '') => { | |
switch(value.constructor.name) { | |
case "Array": return value.map((obj, i) => serialize(i+ "", obj, prefixes(prefix, key))).join('&') | |
case "Object": return parse(value, prefixes(prefix, key)) | |
default: return prefixes(prefix, key) + '=' + value | |
} | |
} | |
const parse = (json, prefix = '') => | |
Object.keys(json) | |
.map(key => serialize(key, json[key], prefix)) | |
.join('&') | |
console.log(parse( | |
{ | |
"searchCriteria": { | |
"pageSize": 10, | |
"filterGroups": [ | |
{ | |
"filters": [ | |
{ | |
"field": "price", | |
"value": 200, | |
"condition_type": "lt" | |
} | |
] | |
}, | |
{ | |
"filters": [ | |
{ | |
"field": "sku", | |
"value": "%red%", | |
"condition_type": "like" | |
} | |
] | |
} | |
] | |
} | |
} | |
)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment