php - need to convert field name with square brackets into a javascript object -


i convert field name consisting of square brackets object in javascript. have seen php convert them array haven't seen 1 done in javascript despite of searching 1 several days.

data:

<input name="address[permanent][name]" type="text" value="my address"> <input name="address[permanent][street][street_one]" type="text" value="my street one"> <input name="address[permanent][street][street_two]" type="text" value="my street two"> 

result (what want achieve):

form = { address: { permanent: { name: "my address", street: { street_one: "my street one", street_two: "my street two" } } } } 

untested, basic algorithm this:

the following works me:

var form = {}; $(':input', yourformelement).each(function(){   var top = form;   var path = $(this).attr('name');   var val = $(this).val();   var prev = '';   while ((path.replace(/^(\[?\w+\]?)(.*)$/, function(_m, _part, _rest) {     prev = path;     _part = _part.replace(/[^a-za-z_]/g, '');     if (!top.hasownproperty(_part)) {       if (/\w+/.test(_rest)) {          top[_part] = {};          top = top[_part];       } else {         top[_part] = val;        }     } else if (!/\w+/.test(_rest)) {       top[_part] = val;     } else {       top = top[_part];     }     path = _rest;   })) && (prev !== path)); }); 

substitute yourformelement jquery expression desired form element.

that iterates on each :input element (form inputs) , each loop attempts break down "path" of name using regular expression, @ same time creating and/or traversing form data-structure being built up. value of input assigned leaf node has been traversed to.

example of working: http://jsfiddle.net/8fplx/10/

that series of conditions inside while loop simplified a lot, works.


Comments

Popular posts from this blog

assembly - 8086 TASM: Illegal Indexing Mode -

Java, LWJGL, OpenGL 1.1, decoding BufferedImage to Bytebuffer and binding to OpenGL across classes -

javascript - addthis share facebook and google+ url -