Handle object in Node via bank return

Asked

Viewed 20 times

0

I’m assembling an object according to the values returned by the database. Actually, I’m doing it this way:

let games;

execSQLQuery(query, form_values)
        .then(dbResponse => {
            if (dbResponse != "") {
                for(let i = 0; i < dbResponse.length; i++){
                    games =[{
                        name: dbResponse[i].nome_sg,
                        evaluation: dbResponse[i].heuristic_status,
                        cod_sg: dbResponse[i].cod_sg
                    }];
                }

It turns out that if the return is composed of more than one group of values, my object only receives the value of the last.

1 answer

1


What happens is that you are changing the value of games after each iteration. Instead of alter all the array, you must add a new object after each iteration.

Suppose the code below (what you currently do):

const items = [1, 2, 3, 4, 5]
let newItems = []

for (const item of items) {
  const toAdd = item * 2
  console.log('Alterando para', toAdd)
  
  // Note abaixo que, por estarmos utilizando o operador de atribuição (`=`), substituimos,
  // a cada iteração, o valor de `newItems`. Isso não é o que queremos.
  newItems = [toAdd]
}

console.log(newItems)

So to solve this, we need to add the item of each iteration to the array. To do this, let’s use the method push:

const items = [1, 2, 3, 4, 5]
const newItems = []

for (const item of items) {
  const toAdd = item * 2
  console.log('Adicionando', toAdd)
  
  // Note abaixo que, ao invés de substituirmos todo o array `newItems` após
  // cada iteração, estamos adicionando o valor do loop atual ao array existente.
  // Para isso, estamos utilizando o `Array.prototype.push`:
  newItems.push(toAdd)
}

console.log(newItems)

So in your example, you need to do the following:

// Precisamos inicializar `games` como um `array` vazio:
const games = []

execSQLQuery(query, form_values).then((dbResponse) => {
  if (dbResponse != '') {
    for (let i = 0; i < dbResponse.length; i++) {
      // Abaixo estamos utilizando o método `push` para adicionar o objeto
      // da iteração atual ao array `games`:
      games.push({
        name: dbResponse[i].nome_sg,
        evaluation: dbResponse[i].heuristic_status,
        cod_sg: dbResponse[i].cod_sg
      })
    }
  }
})
  • 1

    perfect, Luiz, thank you very much! your explanation was sensational

Browser other questions tagged

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