Skip to content

Instantly share code, notes, and snippets.

@kynatro kynatro/params.js
Last active Aug 9, 2018

Embed
What would you like to do?
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
You can’t perform that action at this time.