Transform a Json Array into another JSON using Node

Asked

Viewed 756 times

3

Good morning,

I’m having a problem assembling a JSON using Nodejs. I have a return of a giant SQL that basically follows the structure below.

[
  {
    "numDoc":"0000001",
    "OutrosCampos":"outrosDados",
    "itens":[
      {
        "itemNum":"000000001",
        "nome":"AAAAAAAAA",
        "agrup":"00003",
        "numDoc":"0000001"
      },
      {
        "itemNum":"000000002",
        "nome":"BBBBBBB",
        "agrup":"00003",
        "numDoc":"0000001"
      },
      {
        "itemNum":"000000003",
        "nome":"CCCCCCCCCC",
        "agrup":"00003",
        "numDoc":"0000001"
      }
    ]
  }
]

and I need my JSON to follow the following output structure:

[
  {
    "numDoc":"0000001",
    "OutrosCampos":"outrosDados",
    "itens":[
      {
        "agrup":"00003",
        "itensAgrup":[
          {
            "itemNum":"000000001",
            "nome":"AAAAAAAAA"
          },
          {
            "itemNum":"000000002",
            "nome":"BBBBBBB"
          }
        ]
      },
      {
        "agrup":"00004",
        "itensAgrup":[
          {
            "itemNum":"000000003",
            "nome":"CCCCCCCCCC"
          }
        ]
      }
    ]
  }
]

In short, I need the first array (which has the numDoc) remain intact, that the second array (the items) is separated by an array by the grouping, in which the repeated field numDOC no longer appears and nor the grouping if possible.

I am using nodejs and also several "Packages" as the underscore but I am not able to transform the array in this JSON.

NOTE: I need to read key and value, because this structure can vary the field names and the amount of items, so I can’t try to put in a fixed "array".

Any doubt, you can talk.
Thanks for your help from now on.

3 answers

2


Using pure javascript, it was as follows:

var retorno = [{
  "numDoc": "0000001",
  "OutrosCampos": "outrosDados",
  "itens": [{
    "itemNum": "000000001",
    "nome": "AAAAAAAAA",
    "agrup": "00003",
    "numDoc": "0000001"
  }, {
    "itemNum": "000000002",
    "nome": "BBBBBBB",
    "agrup": "00003",
    "numDoc": "0000001"
  }, {
    "itemNum": "000000003",
    "nome": "CCCCCCCCCC",
    "agrup": "00003",
    "numDoc": "0000001"
  }, {
    "itemNum": "000000004",
    "nome": "CCCCCCCCCC",
    "agrup": "00004",
    "numDoc": "0000001"
  }]
}];

// Variável com o valor final da conversão
var novoRetorno = [];

retorno.map(function(item) {

  // Objeto temporário, será inserido no final
  var tmp = {
    numDoc: item.numDoc,
    OutrosCampos: item.OutrosCampos,
    itens: [],
  };

  // Objeto temporário, será utilizado para armazenar os itens agrupados
  var tmp2 = {};
  item.itens.map(function(item2) {
    // Cria o agrupamento caso não exista, se existir utiliza ele
    tmp2[item2.agrup] = tmp2[item2.agrup] || {};
    // Define o nome do agrup
    tmp2[item2.agrup].agrup = item2.agrup;
    // Resgata os itens já criados ou cria um array vazio
    tmp2[item2.agrup].itensAgrup = tmp2[item2.agrup].itensAgrup || [];
    // Inseri no array de itens o novo item
    tmp2[item2.agrup].itensAgrup.push({
      itemNum: item2.itemNum,
      nome: item2.nome,
    });
  });

  // Loop para remover a key e inserir o objeto puro
  for (var key in tmp2) {
    if (tmp2.hasOwnProperty(key)) {
      tmp.itens.push(tmp2[key]);
    }
  }

  // Insere o objeto final no retorno
  novoRetorno.push(tmp);

});

// Magic!
console.log(novoRetorno);

1

Start by creating a map and then transform to the desired format.

var objeto = [
  {
    "numDoc":"0000001",
    "OutrosCampos":"outrosDados",
    "itens":[
      {
        "itemNum":"000000001",
        "nome":"AAAAAAAAA",
        "agrup":"00003",
        "numDoc":"0000001"
      },
      {
        "itemNum":"000000002",
        "nome":"BBBBBBB",
        "agrup":"00003",
        "numDoc":"0000001"
      },
      {
        "itemNum":"000000003",
        "nome":"CCCCCCCCCC",
        "agrup":"00004",
        "numDoc":"0000001"
      }
    ]
  }
];

var agrupar = objeto[0].itens.reduce(function(obj, item){
    obj[item.agrup] = obj[item.agrup] || [];
    var valores = { "itemNum": item.itemNum, "nome": item.nome };
    obj[item.agrup].push(valores);
    return obj;
}, {});

var grupos = Object.keys(agrupar).map(function(key){
    return {agrup: key, itensAgrup: agrupar[key]};
});

objeto[0].itens = grupos;
console.log(objeto);

reduce and map, allow you to get powerful high-level constructs that can save time and code compared to manual iteration.

  • opa, using your answer, if I wanted to enter another information, before grouping items, type, {... {agrup : 000003, groupname : ZZZZZZZ, items: [... add only this line name agrup, which is, in the original array, along with the code of the items, as it would be ?

0

I never used underscore, but according to the documentation it would work if you applied so, considering resp as the return of SQL:

_.groupBy(resp[0].itens, function(item) { return item.agrup; });

Browser other questions tagged

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