Skip to content

Instantly share code, notes, and snippets.

@eonarik
Created September 27, 2018 17:29
Show Gist options
  • Save eonarik/ce859640a6bc8e5da5aceb06517d84f9 to your computer and use it in GitHub Desktop.
Save eonarik/ce859640a6bc8e5da5aceb06517d84f9 to your computer and use it in GitHub Desktop.
js $_GET to javascript object
// рекурсивное преобразование урл параметров в js object
const get2obj = function () {
let obj = {}
let gets = location.search.substring(1).split('&')
for(var i = 0; i < gets.length; i++) {
let parts = gets[i].split('=')
let keys = decodeURIComponent(parts.shift()).replace(/\[(.*?)\]/g, '.$1').split(/\./)
obj = assignValue({...obj}, keys, parts.join('='), 0)
}
function assignValue (obj, keys, value, index) {
let key = keys.shift()
if (key === '') {
if (!Array.isArray(obj)) {
obj = []
}
if (keys.length !== 0) {
obj.push(assignValue({}, keys, value, ++index))
} else {
obj.push(value)
}
} else {
if (keys.length !== 0) {
obj[key] = assignValue(key in obj ? obj[key] : {}, keys, value, ++index)
} else {
obj[key] = value
}
}
return obj
}
return obj
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment