Created
March 5, 2017 05:20
-
-
Save sheharyarn/b01e8af243245da9ce150a0a0fd32a01 to your computer and use it in GitHub Desktop.
Serialize an Object into URI Query in Javascript
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
| /** | |
| * This method converts a Javascript object into | |
| * a URI query string. Also handles nested arrays | |
| * and objects (in Rails / PHP syntax) | |
| * | |
| * @author Sheharyar Naseer (@sheharyarn) | |
| * @license MIT | |
| * | |
| * @example | |
| * | |
| * let params = { | |
| * a: 100, | |
| * b: 'has spaces', | |
| * c: [1, 2, 3], | |
| * d: { x: 9, y: 8} | |
| * } | |
| * | |
| * serializeQuery(params) | |
| * // returns 'a=100&b=has%20spaces&c[]=1&c[]=2&c[]=3&d[x]=9&d[y]=8 | |
| * | |
| **/ | |
| function serializeQuery(params, prefix) { | |
| const query = Object.keys(params).map((key) => { | |
| const value = params[key]; | |
| if (params.constructor === Array) | |
| key = `${prefix}[]`; | |
| else if (params.constructor === Object) | |
| key = (prefix ? `${prefix}[${key}]` : key); | |
| if (typeof value === 'object') | |
| return serializeParams(value, key); | |
| else | |
| return `${key}=${encodeURIComponent(value)}`; | |
| }); | |
| return [].concat.apply([], query).join('&'); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment