convert JSON to object

1

I have the following json

[
    {"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"}
]

I need to convert to the object below:

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

Hiago gave me the following code:

$('.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;
 });

At the end the return is empty [{"user": {}}], however debugando I see that the data array is filled correctly, it also enters the $ .each, and loads the values passes the values and zeros one by one.

    
asked by anonymous 24.06.2017 / 19:22

2 answers

2

This does not work because you are using the same name obj of variable inside and outside the function.

Instead of

  var obj = {};
  $.each(dados, function (i,obj) {
      obj[obj.name] = obj.value;
  });

usa

  var obj = {};
  $.each(dados, function (i, dado) {
      obj[dado.name] = dado.value;
  });

or simpler:

var obj = dados.reduce(function(obj, dado){
    obj[dado.name] = dado.value;
    return obj;
}, {});
    
25.06.2017 / 03:31
1

You can use the following logic to directly mount the object with the user object inside:

var json = {};
var usuario = {};
$.each(obj, function(i, dado){
   if($.inArray(dado.name, ["login", "senha", "confirma_senha"]) > -1 ){
     usuario[dado.name] = dado.value;
   } else {
     json[dado.name] = dado.value;
   }
});
json["usuario"] = usuario;
    
25.06.2017 / 06:00