Created
April 23, 2019 17:45
-
-
Save juliarose/8abc15bc14d3aaaefc642987bb4df60b to your computer and use it in GitHub Desktop.
Resursive convert object to querystring in the format - numfruits=2&fruits[banana]=yellow&fruits[watermelon]=red&arr[]=first&arr[]=second
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
/** | |
* Convert query object to string | |
* @param {Object} query - Object | |
* @returns {String} Query string | |
*/ | |
function queryString(query) { | |
let encode = encodeURIComponent; | |
/** | |
* Flatten an array | |
* @param {Array} arr - Array to flatten | |
* @param {Boolean} [deep] - Recursive flatten? | |
* @returns {Array} Flattened array | |
*/ | |
function flatten(arr, deep) { | |
return arr.reduce((result, a) => { | |
if (deep && Array.isArray(a)) { | |
return [...result, ...flatten(a)]; | |
} else { | |
return [...result, a]; | |
} | |
}, []); | |
} | |
/** | |
* Get query parameter for value | |
* @param {String} name - Name of value | |
* @param {*} value - Value | |
* @returns {(String|Array)} Query parameter | |
*/ | |
function getQuery(name, value) { | |
if (Array.isArray(value)) { | |
return value.map((subvalue) => { | |
return getQuery(name + '%5B%5D', subvalue); | |
}); | |
} else if (typeof value === 'object') { | |
return Object.keys(value).map((subname) => { | |
return getQuery(`${name}%5B${encode(subname)}%5D`, value[subname]); | |
}); | |
} else { | |
return name + '=' + encode(value); | |
} | |
} | |
return flatten(Object.keys(query).map((name) => { | |
return getQuery(encode(name), query[name]); | |
}), true).join('&'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment