Created
July 14, 2015 19:46
-
-
Save jrop/b5f56c11628edf997c97 to your computer and use it in GitHub Desktop.
toQueryString.js
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 toQueryString(obj, urlEncode) { | |
// | |
// Helper function that flattens an object, retaining key structer as a path array: | |
// | |
// Input: { prop1: 'x', prop2: { y: 1, z: 2 } } | |
// Example output: [ | |
// { path: [ 'prop1' ], val: 'x' }, | |
// { path: [ 'prop2', 'y' ], val: '1' }, | |
// { path: [ 'prop2', 'z' ], val: '2' } | |
// ] | |
// | |
function flattenObj(x, path) { | |
let result = [ ] | |
path = path || [] | |
Object.keys(x).forEach(key => { | |
if (!x.hasOwnProperty(key)) | |
return | |
let newPath = path.slice() | |
newPath.push(key) | |
let vals = [ ] | |
if (typeof x[key] == 'object') { | |
vals = flattenObj(x[key], newPath) | |
} else { | |
vals.push({ path: newPath, val: x[key] }) | |
} | |
vals.forEach(obj => result.push(obj)) | |
}) | |
return result | |
} // flattenObj | |
// start with flattening `obj` | |
let parts = flattenObj(obj) // [ { path: [ ...parts ], val: ... }, ... ] | |
// convert to array notation: | |
parts = parts.map(varInfo => { | |
if (varInfo.path.length == 1) | |
varInfo.path = varInfo.path[0] | |
else { | |
let first = varInfo.path[0] | |
let rest = varInfo.path.slice(1) | |
varInfo.path = first + '[' + rest.join('][') + ']' | |
} | |
return varInfo | |
}) // parts.map | |
// join the parts to a query-string url-component | |
let queryString = parts.map(varInfo => varInfo.path + '=' + varInfo.val).join('&') | |
if (urlEncode) | |
return encodeURIComponent(queryString) | |
else | |
return queryString | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment