JSFiddle - React, Tailwind, and code Playground
by WilsonPage
HTML
<form>
<input type='text' name='name' placeholder='Name'>
<input type='text' name='contact.tel' placeholder='Telephone'>
<input type='text' name='contact.email.a.one' placeholder='Email One'>
<input type='text' name='contact.email.a.two' placeholder='Email Two'>
<input type='text' name='contact.email.a.three' placeholder='Email Three'>
<input type='text' name='contact.twitter' placeholder='Twitter'>
<input type='text' name='contact.address.street' placeholder='Street'>
<input type='text' name='contact.address.town.home' placeholder='Town'>
<button>SUBMIT</button>
</form>
JavaScript
/***************************************************
** PLUGIN
***************************************************/
(function($){
$.fn.objectify= function() {
var inputs = $(this).find('input'),
result = {};
// loop over each of the input fields
inputs.each(function(i) {
var input = $(this),
name = input.attr('name'),
value = input.val(),
array = name.split('.'),
len = array.length,
currentlevel = {};
// loop over array of levels eg. ['contact', 'address', 'town']
for(var i = 0; i < len; i++){
// cache the key
var key = array[i];
// if there is no top level key: create it
if(i==0 && !result[key]) { result[key] = {} };
// if this is the top level: set the current level
// to the top of the result object
if(i==0){ currentlevel = result };
if(i == len-1){// if last level:
// set the value on the current key
currentlevel[key] = value
}else{// else if more levels to come:
// get the next key
var nextKey = array[i+1];
// if there is no next key, create it
if(!currentlevel[key][nextKey]) { currentlevel[key][nextKey] = {} };
// move the current level reference down one level
currentlevel = currentlevel[key];
}
}
});
// return form data
return result;
}
})(jQuery);
/***************************************************
** USAGE
...