Created
March 28, 2013 12:26
-
-
Save RSully/5262735 to your computer and use it in GitHub Desktop.
Parse input "arrays" in JS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function parseInputs(data) { | |
var ret = {}; | |
retloop: | |
for (var input in data) { | |
var val = data[input]; | |
var parts = input.split('['); | |
var last = ret; | |
for (var i in parts) { | |
var part = parts[i]; | |
if (part.substr(-1) == ']') { | |
part = part.substr(0, part.length - 1); | |
} | |
if (i == parts.length - 1) { | |
last[part] = val; | |
continue retloop; | |
} else if (!last.hasOwnProperty(part)) { | |
last[part] = {}; | |
} | |
last = last[part]; | |
} | |
} | |
return ret; | |
} | |
var data = { | |
"nom": "123", | |
"items[install][item_id_4]": "4", | |
"items[install][item_id_5]": "16", | |
"items[options][takeover]": "yes" | |
}; | |
var out = parseInputs(data); | |
console.log('\n***Moment of truth:\n'); | |
console.log(out); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment