Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save dabernathy89/0825659dd0096c8144bcebdadb964da3 to your computer and use it in GitHub Desktop.
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).
/*
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}` : '';
}
@yuoppp
Copy link

yuoppp commented May 29, 2020

You also need a custom parseQuery function or this.$route.query will be { 'foo[]': ['bar', 'buzz'] } instead of { foo: ['bar', 'baz'] }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment