JSFiddle - React, Tailwind, and code Playground

by Joe Saad

HTML

<form action="">
  Player Name<input type="text" name="player.name"> <br> Player Club<input type="text" name="player.club"> <br> Player City<input type="text" name="player.city"> <br> Sport Name<input type="text" name="sport.name"> <br> Sport League<input type="text"
    name="sport.league"> <br> Sport Country<input type="text" name="sport.country"> location <input type="checkbox" name="location.on"> Address 1 <input type="text" name="reachable.address.address1"> Address 2 <input type="text" name="reachable.address.address2">  Zipcode <input type="text" name="reachable.address.zipcode">
  <input type="text" name="reachable.address.address1">
  <button type="submit">Submit</button>
</form>

JavaScript

//player
function constructObj(formObj, q) {
  console.log('calling function')
  console.log(formObj)
  var cName = q.name ? q.name : q;
  console.log(cName)
  if (cName.indexOf(".") > -1) {
    var myNewAttr = cName.substr(0, cName.indexOf("."));
    console.log('mynew: ' + myNewAttr)
    //constructObj(formObj, q);
  } else {
    console.log('else ')
    if (formObj.hasOwnProperty(cName)) {
      console.log(formObj)
      var newkey = cName.substr(cName.indexOf(".") + 1);
      formObj[cName][newkey] = q.value
    } else {
      formObj[cName] = {}
      console.log('1^^^^^^^^^^^^^^^^^^^^^^')
      console.log(cName)
      var newkey = cName.substr(cName.indexOf(".") + 1);
      console.log(cName)
      console.log('2^^^^^^^^^^^^^^^^^^^^^^')
      console.log(newkey)
      console.log('3^^^^^^^^^^^^^^^^^^^^^^')
      if (newkey.indexOf('.') > -1)
        constructObj(formObj, newkey);
    }
  }

  result = formObj
}

$("button").click(function(e) {
  e.preventDefault();
  var result = {};
  $.each($("form").serializeArray(), function() {
    constructObj(result, this)
  });
  console.log(result);
});