Transform an Json Array into another JSON using node

3

Good morning,

I'm having a problem mounting a JSON using NodeJS. I have a return from 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"
      }
    ]
  }
]

I need to have my JSON 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 ) to remain intact, that the second array (the items) be separated by an array by the array, in which there is no longer the repeated field in a DOC and neither the array If it was 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, since this structure can vary the field names and quantity of items, so I can not try to put it in a fixed array.

Any doubt, you can speak. Thanks for the help right away.

    
asked by anonymous 10.07.2017 / 12:43

3 answers

2

Using pure javascript, it looks like this:

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);
    
10.07.2017 / 13:47
1

Start by creating a mapping and then transform it into 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 builds that can save time and code compared to manual iteration.

    
10.07.2017 / 13:52
0

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

_.groupBy(resp[0].itens, function(item) { return item.agrup; });
    
10.07.2017 / 15:27