convert JSON to object

Asked

Viewed 2,539 times

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

need 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 passed 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;
 });

In the end the return is empty [{"user":{}}], but debugging I see that the data array is filled correctly, it also enters in $.each, and loads the values passes the values and Zera one by one.

2 answers

2


That doesn’t work because you’re using the same name obj variable in and out of the function.

In view of

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

uses

  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;
}, {});

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;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.