Is there a better way to convert a URL\'s location.search as an object? Maybe just more efficient or trimmed down? I\'m using jQuery, but pure JS can work too.
JSON Parse after stringify does the job of converting to a json with array data.
?key1=val1&key2[]=val2.1&key2[]=val2.2&key2[]=val2.3&
{
'key1' : 'val1',
'key2' : [ 'val2.1', 'val2.2', 'val2.3' ]
}
function QueryParamsToJSON() {
var list = location.search.slice(1).split('&'),
result = {};
list.forEach(function(keyval) {
keyval = keyval.split('=');
var key = keyval[0];
if (/\[[0-9]*\]/.test(key) === true) {
var pkey = key.split(/\[[0-9]*\]/)[0];
if (typeof result[pkey] === 'undefined') {
result[pkey] = [];
}
result[pkey].push(decodeURIComponent(keyval[1] || ''));
} else {
result[key] = decodeURIComponent(keyval[1] || '');
}
});
return JSON.parse(JSON.stringify(result));
}
var query_string = QueryParamsToJSON();