Last active
May 29, 2020 09:32
-
-
Save dabernathy89/0825659dd0096c8144bcebdadb964da3 to your computer and use it in GitHub Desktop.
An implementation of the Vue Router `stringifyQuery` method which handles nested query parameters. It uses square brackets (`[]`) for query parameter arrays (regular and nested).
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
/* | |
Ex: | |
stringifyQuery({foo: "bar", baz: ['a','b'], fizz: {foo: [1,2,3], bar: {bees: "knees"}}}); | |
-> ?foo=bar&baz[]=a&baz[]=b&fizz[foo][]=1&fizz[foo][]=2&fizz[foo][]=3&fizz[bar][bees]=knees | |
Square brackets will be URL encoded; I didn't do so in this example for readability. | |
*/ | |
function stringifyQuery (obj, parentName) { | |
const res = obj ? Object.keys(obj).map(key => { | |
const val = obj[key]; | |
if (parentName) { | |
key = parentName + '[' + key + ']'; | |
} | |
if (val === undefined) { | |
return ''; | |
} | |
if (val === null) { | |
return encodeURIComponent(key); | |
} | |
if (!Array.isArray(val) && typeof val === "object") { | |
return stringifyQuery(val, key).slice(1); | |
} | |
if (Array.isArray(val)) { | |
const result = []; | |
val.forEach(val2 => { | |
if (val2 === undefined) { | |
return; | |
} | |
if (val2 === null) { | |
result.push(encodeURIComponent(key + '[]')); | |
} else { | |
result.push(encodeURIComponent(key + '[]') + '=' + encodeURIComponent(val2)); | |
} | |
}) | |
return result.join('&'); | |
} | |
return encodeURIComponent(key) + '=' + encodeURIComponent(val); | |
}).filter(x => x.length > 0).join('&') : null; | |
return res ? `?${res}` : ''; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You also need a custom
parseQuery
function orthis.$route.query
will be{ 'foo[]': ['bar', 'buzz'] }
instead of{ foo: ['bar', 'baz'] }