How to read this JSON correctly? MSSQL and Node

3
{
  "recordsets": [
    [
      {
        "IdUsuario": 5152490,
        "strNome": "Roberto ",
        "IdPapel": 1
      },
      {
        "IdUsuario": 5152490,
        "strNome": "Roberto ",
        "IdPapel": 3000001
      }
    ]
  ]

I'm trying to return to the client only its permissions (IdPapel), however, I'm not getting it.

The code that performs the query follows and returns the resulting JSON:

function verify(query, res, user) {
  sql.connect(dbConfig, (err) => {
    if (err) {
      console.log("Error while connecting database :- " + err);
      res.sendStatus(403);
      sql.close();
    } else {
      var request = new sql.Request();
      request.query(query, (err, result) => {
        if (err) {
          console.log("Error while querying database :- " + err);
          res.sendStatus(403);
          sql.close();
        } else {
          res.send(result);
          sql.close();
        }
      });
    }
  });
}

Any tips?

Thank you!

    
asked by anonymous 30.11.2018 / 18:03

1 answer

4

To have an array where each element is a IdPapel , you need to access the array of users returned by the query to the Database. Assuming the response is stored in the result variable, we can do:

const respostaDecodificada = result
// Aqui estamos pegando o array com os usuários
const arrayUsuarios = respostaDecodificada.recordsets[0]
// Aqui estamos criando um novo array, com o IdPapel de cada usuário
const arrayIdPapel = arrayUsuarios.map(usuario => usuario.IdPapel)

And after executing the code, if we give a console.log(arrayIdPapel) we will get: [ 1, 3000001 ] . From what you commented that's what you wanted. Then just do res.send(arrayIdPapel) .

    
30.11.2018 / 18:27