change data JSON.stringify

0

I have a form with several fields when, I have a function that when submitting the form captures the fields:

$('.form').submit(function () {
                var dados = JSON.stringify(jQuery(this).serializeArray());
                alert(dados);
                return false;
            });

The fields returned in data are:

[{"name":"razao_social","value":"INTELIDER"},
{"name":"nome_fantasia","value":"INTELIDER LTDA"},
{"name":"cpf_cnpj","value":"10.999.558/0001-86"},
{"name":"rg_insc_estadual","value":"132456789"},
{"name":"login","value":"gleyson"},
{"name":"senha","value":"123456"},
{"name":"confirma_senha","value":"S"}]"

But I need you to look like this:

[
  {
      "razao_social": "INTELIDER",
      "nome_fantasia": "INTELIDER LTDA",
      "cpf_cnpj": "10999558000186",
      "rg_insc_estadual": "132456789",
      "usuario":       {
         "login": "gleyson",
         "senha": "123456",
         "ativo": "S"
      },
   }
]

Remembering that I need to remove a confirm_password from the first code and add the active field from the second example to send this Json.

    
asked by anonymous 24.06.2017 / 17:01

1 answer

0

You can do the conversion for an object:

$('.form').submit(function () {
      var dados = jQuery(this).serializeArray();
      var obj = {};
      $.each(dados, function (i,obj) {
          obj[obj.name] = obj.value;
      });

      obj.usuario = {
            login: obj.login,
            senha: obj.senha,
            ativo: obj.confirma_senha
      };

      var json = JSON.stringify([obj]);
      alert(json);
      return false;
 });

If you prefer you can use the jquery serializeObject plugin:

$.fn.serializeObject = function() {
    var o = Object.create(null),
        elementMapper = function(element) {
            element.name = $.camelCase(element.name);
            return element;
        },
        appendToResult = function(i, element) {
            var node = o[element.name];

            if ('undefined' != typeof node && node !== null) {
                o[element.name] = node.push ? node.push(element.value) : [node, element.value];
            } else {
                o[element.name] = element.value;
            }
        };

    $.each($.map(this.serializeArray(), elementMapper), appendToResult);
  }
  

How to use:

$('.form').submit(function () {
      var dados = jQuery(this).serializeObject();
      var json = JSON.stringify([dados]);
      alert(json);
      return false;
 });
    
24.06.2017 / 17:10