JSFiddle - React, Tailwind, and code Playground

by Сергей Тарасевич

HTML

<form class="form" data-form="serialize">
  <input type="text" name="text1" value="name=text1">
  <input type="text" name="text2[]" value="name=text2[] 1">
  <input type="text" name="text2[]" value="name=text2[] 2">
  <input type="text" name="text2[]" value="name=text2[] 3">
  <select name="select">
    <option value="option1">value=option1</option>
    <option value="option2">value=option2</option>
    <option value="option3">value=option3</option>
  </select>
  <textarea name="textarea123">name=textarea123</textarea>
  <div class="radioCheckboxForm">
    <input type="radio" name="radio" value="name=radio 1" checked="checked">
    <input type="radio" name="radio" value="name=radio 2">
  </div>
  <div class="radioCheckboxForm">
    <input type="checkbox" name="checkbox1" value="name=checkbox1">
    <input type="checkbox" name="checkbox2" value="name=checkbox2">
    <input type="checkbox" name="checkbox3" value="name=checkbox3">
  </div>
  <button type="submit">Обновить</button>
</form>

CSS

.form input[type="text"],
.form select,
.form textarea,
.form button {
  box-sizing: border-box;
  display: block;
  margin: 10px 10px 0;
  outline: 0 solid transparent;
  padding: 3px 6px;
  width: 250px;
}

.form .radioCheckboxForm {
  box-sizing: border-box;
  display: block;
  margin: 10px 10px 0;
  padding: 3px 6px;
  text-align: center;
  width: 250px;
}

.form .radioCheckboxForm input[type="checkbox"],
.form .radioCheckboxForm input[type="radio"] {
  display: inline-block;
  vertical-align: middle;
  height: 20px;
  width: 20px;
}

JavaScript

var serializeObject = {
  doc: $(document),
  fn: function(a) {
    var arr = a.serializeArray();
    var tree = {};
    $.each(arr, function(index, object) {
      var node = tree;
      var name = object.name;
      var value = object.value;
      var parts = name.match(/[^\[\]]+(\[\])?|\[[^\]]+\](\[\])?/g);
      if (parts) {
        $.each(parts, function(i, key) {
          var isArray = /\[\]$/.test(key);
          key = key.replace(/(\[|\])/g, '');

          if (!isArray) {
            if (!node[key]) {
              node[key] = (i == (parts.length - 1)) ? value : {};

            }

          } else {
            if (!node[key]) {
              node[key] = [];

            }

            if (typeof value === 'object') {
              node[key] = arrayUnique(node[key].concat(value));

            } else {
              node[key].push(value);

            }

          }
          node = node[key];

        });

      }

    });
    return tree;

  }

}
serializeObject.doc.on('click', '[data-form="serialize"] button', function() {
  var a = serializeObject.fn($('[data-form="serialize"]'));
  console.log(a);
  return false;
});