javascript - Convert complex input names to array -
i have complex input names like: this[is][][a][complex][name]
, need convert array/object. like:
{ "this": { "is": [ { "a": { "complex": { "name": true } } } ] } }
how can pure javascript or jquery?
reason
i need send jquery.ajax() method like:
jquery.ajax({ "data": { "complex": complex_names, "time": date.now() }, ... });
if serialize data this[is][][a][complex][name]=true
, broke http request, , sends data[this[is][][a][complex][name]]
instead of data[this][is][][a][complex][name]
.
example
i did example you. well, suppose have this:
<input type="text" name="test1" value="ok" /> <input type="text" name="test2" value="ok" /> <input type="text" name="test3[1]" value="ok" /> <input type="text" name="test4[1][2]" value="ok" /> <input type="text" name="test5[]" value="ok" />
if send directly via post, it'll generate request like:
test1: ok test2: ok test3[1]: ok test4[1][2]: ok test5[]: ok
but need send via jquery.ajax() method, inside of array in data
option (like complex_data
other data). request similar to:
call_time: 1612 call_title: test complex_data[test1]: ok complex_data[test2]: ok complex_data[test3][1]: ok complex_data[test4][1][2]: ok complex_data[test5][]: ok
note form input set inside complex_data
object. if convert data array, like:
{ "test1": "ok", "test2": "ok", "test3[1]": "ok", "test4[1][2]": "ok", "test5[]": "ok", }
and send complex_data
, it'll request it, instead:
ta). request similar to:
call_time: 1612 call_title: test complex_data[test1]: ok complex_data[test2]: ok complex_data[test3][1]]: ok complex_data[test4][1][2]]: ok complex_data[test5][]]: ok
simplified case test1
nad test2
work fine, complex cases test3[1]
not understand , broke.
workaround
currently i'm using workaround solution create array like: this][is][][a][complex
, included http request data[...]
turn data[
this][is][][a][complex][name
]
.
research
it's similar how convert input name javascript array question, bit more complex because deepness 0 infinite (generally level 3). so, can't make unless use eval (!).
interesting problem, here came with:
function convert(s) { var names = s.replace(/^\w+/, "$&]").replace(/]$/, "").split("]["); var result = {}; var obj = result; var last; (var = 0; < names.length; i++) { var name = names[i]; if (typeof last !== "undefined") { obj[last] = name === "" ? [] : {}; obj = obj[last]; } last = name === "" ? 0 : name; } obj[last] = true; return result; }
jsfiddle: http://jsfiddle.net/qdrvz/
Comments
Post a Comment