Skip to content

Instantly share code, notes, and snippets.

@kynatro
Last active August 9, 2018 20:47
Show Gist options
  • Save kynatro/689b6dc85b0f0bea2af070b1f6beec0a to your computer and use it in GitHub Desktop.
Save kynatro/689b6dc85b0f0bea2af070b1f6beec0a to your computer and use it in GitHub Desktop.
URL Parameters as an object
// Could be any query string
var parameters = document.location.search;
var parametersObject = parameters
// Skip the "?" at the beginning of the string
.substr(1)
// Split into an array of individual parameters
.split("&")
// Split each parameter into an array of its key and value
.map(function(a){
return a.split("=");
})
// Build a single depth object out of each key/value pair
.reduce(function(m,i){
// If this key already exists, its an array, so append to it instead of defining it
if(m[i[0]]) {
// Make this into an Array if it isn't one already
if(m[i[0]] && m[i[0]].constructor !== Array) {
m[i[0]] = [m[i[0]]];
}
m[i[0]].push(decodeURIComponent(i[1]));
} else {
m[i[0]] = decodeURIComponent(i[1]);
}
return m;
}, {});
document.location.search.substr(1).split("&").map((a) => a.split("=")).reduce((m,i) => { if(m[i[0]]) { if(m[i[0]] && m[i[0]].constructor !== Array) { m[i[0]] = [m[i[0]]] } m[i[0]].push(decodeURIComponent(i[1])) } else { m[i[0]] = decodeURIComponent(i[1]) } return m }, {})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment