javascript - How would I dynamically convert form fields to multi-dimensional js object? -


i'm struggling dynamically convert set of inputs multi-dimensional object passing in ajax call.

assume have person, multiple addresses. fields this:

<input name='person[name]' value='bradley'/> <input name='person[addresses][home]' value='123 anywhere drive.'/> <input name='person[addresses][work]' value='456 anywhere road.'/> 

how 1 convert fields ab object looks this:

person : {     name: 'bradley',     addresses:     {         home: '123 anywhere drive.',         work: '456 anywhere road.'     } } 

i need dynamically (function needs work regardless of inputs provided) , work @ n-depth.

(note: jquery available).

http://jsfiddle.net/w4wqh/1/

honestly think there's way in regex.. couldn't figure out. so, it's bit of ugly string manipulation. either way, should on right track think:

function serialize () {     var serialized = {};     $("[name]").each(function () {         var name = $(this).attr('name');         var value = $(this).val();          var namebits = name.split('[');         var previousref = serialized;         for(var = 0, l = namebits.length; < l;  i++) {             var namebit = namebits[i].replace(']', '');             if(!previousref[namebit]) {                 previousref[namebit] = {};             }             if(i != namebits.length - 1) {                 previousref = previousref[namebit];             } else if(i == namebits.length - 1) {                 previousref[namebit] = value;             }         }     });     return serialized; }  console.log(serialize()); 

quick explanation. grabs 'name' attribute, , iterates on them. each iteration, grabs name , splits on '['. gets how far object need put things. so, person[addresses][work], person, addresses], work].

then, there's tricky part. since objects passed around reference, can see if serialized variable has 'person' in it. if not, adds it, , sets value empty object.. generic enough used storing more things, or replaced if necessary. if there no more levels need go through, takes value of element , assigns reference has. otherwise, code grabs reference whatever made, , loops again, performing same operation. so, person[addresses][work]..

  1. does serialized.person exist? no. setting serialized.person {}. not end of loop, store reference serialized.person previousref.
  2. does previousref.addresses exist? (serialized.person.addresses) no. setting previousref.addresses {}. not end of loop, store reference previousref.addresses previousref.
  3. does previousref.work exist? (serialized.person.addresses.work) no. setting previousref.work {}. wait. end of loop. setting previousref.work value in element.

Comments

Popular posts from this blog

css - Which browser returns the correct result for getBoundingClientRect of an SVG element? -

gcc - Calling fftR4() in c from assembly -

Function that returns a formatted array in VBA -