How to take the third value of an object array

Asked

Viewed 170 times

-3

First of all, I’ve already researched about, but I couldn’t, at least not in a simple way and it was supposed to work. Well I have a variable that contains this following array when I give a console

[
 {
  Id: 1,
  User: 'User',
  Password: 'Dn',
  Nome: 'Fhdnd',
  Sobrenome: 'Js'
 } 
]

This is the array of users, but this I want to get only the password? It was not supposed to work with rows[2] ? What I hoped was that you would return:

[
  {
    Password: 'Dn'
  }
]

Error: Undefined

The only way I can achieve this goal is with foreach?

Obs: Rows is the name of the variable that contains this array

My full function where I’m trying to solve the problem

async function verify(req,res,username,password){
 db.serialize(async function (){                               
  const query = 'SELECT * from Users WHERE User = (?) AND Password = (?)'                                                     
 db.all(query,[username, password],async function(err,rows){    
  try{
   if(rows.length == 1){                                          
    console.time("time1")                                         
    await console.log(rows);                                      
    console.log("Correct user");                                                                                                                
    res.render(__dirname + "/View/Home/index.handlebars");
    rows[2]                                          
    console.timeEnd("time1")                                       
     }
    else{
     console.log("Incorrect user!")}}
    catch{
    console.error("\x1b[31m","Problema com a função de autenticação, erro: \n", err);
    }
  })
})}

This is where I want to access the index exactly, I’m calling the function, I just didn’t post everything because this is where the function should show the index I want to access etc ... I’m just not posting the rest because I’m not having a problem with the rest of my code.

It may be that I come from more than one object in the array, ie I will add more users over time.

  • Comment on what to improve on the question because it seems clear to me.

  • William, what you have is an array with an object inside.

  • And how to access this password? To be able to display only the password and not the entire array

  • I’ve already edited the August question

  • 1

    Assign those values to a variable. And, based on your code, for you to access the password, it would look like this: array[0]. Password

  • Above, "array" would be the name of the variable. Take a closer look at this code: https://codepen.io/Kravin/pen/XWjBwRQ

  • But these values need to be dynamic because I might delete some user or create one, and I will use these values in another file so it would be kind of complicated if I have 100 users downloads? Then I would have to add 100 times these values into a variable.

  • You can convert my "array" to json to achieve my goal?

  • There really would have to be a foreach. Add this information to the question, which may be several objects within the array, so we can elaborate the correct answer.

  • Okay, sorry kkk.

  • Of good, Guillermo.

  • 2

    Boy, the guys here like to downvote everything, huh?

Show 7 more comments

1 answer

1


Buddy, I’ve done three ways here to try to solve your problem. The first is to display in case it is an array with only one object (which was the one initially presented in your question). The other two shapes are distinct ways of doing the same thing when we have a list of objects (an array with multiple objects).

Code in case it is an array with only 1 object:

let usuarios = [{
  Id: 1,
  User: 'User',
  Password: 'Dn',
  Nome: 'Fhdnd',
  Sobrenome: 'Js'
}]

console.log(usuarios[0].Password);

Now two distinct ways of traversing an array of objects (a list of objects), which is what it really seems to be your need.

let usuarios = [{
    Id: 1,
    User: 'User',
    Password: 'Dn',
    Nome: 'Fhdnd',
    Sobrenome: 'Js'
  },
  {
    Id: 2,
    User: 'User2',
    Password: 'Cn',
    Nome: 'Alombra',
    Sobrenome: 'PHP'
  },
  {
    Id: 3,
    User: 'User3',
    Password: 'Fn',
    Nome: 'Dinamic',
    Sobrenome: 'Java'
  }
]

/* 1ª forma */
usuarios.forEach(item => {
  console.log(item.Password);
});

console.log('-----');

/* 2ª forma */
for (key in usuarios) {
  console.log(usuarios[key].Password);
}

I hope I’ve helped.

OBS: Add this part below to give further information on a question that the questioner has shown to have in the comments. Below is an example of an Array and manipulation of it.

Array:

frutas = ["morango", "laranja", "abacaxi", "banana"];

console.log(frutas[3]); //Acessando elemento de um array

  • Javascript NAY works with Associative Array, this form below does not work in Javascript (this array statement would work in PHP for example). Behold:

array = ["id" => 1, "nome" => "Bruno", "idade" => 19, "email" => "[email protected]"];
console.log(array["nome"]);

Above, it will give error. To work with associative indexes, in JS, the best way is to work in object form. See the links below for better information:

Arrays

Alternative to work with Associative indexes in JS

  • It worked here vlw guy, but it wasn’t supposed to work like this either rows[2] ? Why would it be taking the second index of the array since it starts at 0, or it doesn’t work because it’s not an array but an array that contains an object?

  • 1

    I’m glad it worked out for you, William. As you said, this way that you are quoting "Rows[2]" does not work precisely because it contains an object within the array. You would only be able to access it in this way that you mentioned, if it was a normal array (array with key and value), where "2" there would be the key. To access an array of vc objects you must access the key of the array (as you mentioned), then access the object you want (hence the foreach or other repeat structure) and finally access the property of that object you want (Id, User, Password...).

  • 1

    I will add at the end of the answer a representation of a normal array, which would be picked up in the form you quoted.

Browser other questions tagged

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