Restful API with NodeJS and Mysql with Multiple Columns (I want to return json in levels)

1

Alright. Can anyone help me with a question of Angular, or API with Node.js?

I have a mysql api with Node.js with inner join in 2 tables, but of course mysql returns everything in a single array, but I think it is more correct and feasible to return the arrays in level.

Example returning mysql direct results:

[
    {
        coluna1: 'AAAAA',
        coluna2: 'XXXXX'
    },{
        coluna1: 'AAAAA',
        coluna2: 'YYYYY'
    },{
        coluna1: 'BBBBB',
        coluna2: 'ZZZZZ'
    },
]

What I want is to turn it into this:

[
    {
        coluna1: 'AAAAA',
        outra_arary: [
            {
                coluna2:  'XXXXX'
            },{
                coluna2:  'YYYYY'
            }
        ]
    },{
        coluna1: 'BBBBB',
        outra_arary: [
            {
                coluna2:  'ZZZZZ'
            }
        ]
    }
]

An example of how the method is:

router.get('/', (req, res, next) => {
    res.locals.connection.query('select *
                                   from tabela1
                             inner join tabela2
                                on tabela1.id = tabela2.id;', (error, results, fields) => {
        if (error) {
            res.send({
                "status" : 500,
                "error" : error,
                "response" : null
            });
        } else {
            res.send({
                "status" : 200,
                "error" : null,
                "response" : results
            });
        }
    });
});
    
asked by anonymous 11.06.2018 / 19:52

1 answer

0

One idea is to use:

// Exemplo de resposta do MYSQL
const resultados = [
  {
      coluna1: 'AAAAA',
      coluna2: 'XXXXX'
  },{
      coluna1: 'AAAAA',
      coluna2: 'YYYYY'
  },{
      coluna1: 'BBBBB',
      coluna2: 'ZZZZZ'
  },
]

// Função que retorna o array "outra_array", que contém vários objetos com os dados de coluna2
function retornaColuna(coluna) {
  const colunaFiltrada = new Array()
  resultados.forEach(valor => {
    if(valor.coluna1 == coluna)
      colunaFiltrada.push({ coluna2: valor.coluna2 })
  })
  return colunaFiltrada
}

// Itera sobre o array de resposta do MYSQL, criando a estrutura desejada. Nesse caso, coluna1 pode estar repetido.
let resposta = new Array()
resultados.forEach(valor => {
  resposta.push({ coluna1: valor.coluna1, outra_array: retornaColuna(valor.coluna1) })
})

// Remove as colunas1 duplicadas.
resposta = resposta.filter((a) => !this[JSON.stringify(a)] && (this[JSON.stringify(a)] = true))

console.log(resposta) // Retornará o resultado esperado

The last function, which removes possible duplicate objects in the Array, is available here in Stack

    
11.06.2018 / 20:48