How can I access any item from a list in a function? I can only use a specific list item in a function and I can't figure out how to use any list item I want. If I want to use the second item in a list, I have no idea how to do it.
var database = [
{
username: "captain",
password: "america"
},
{
username: "bruce",
password: "banner"
},
{
username: "tony",
password: "stark"
}
]
var usernamePrompt = prompt("Enter your name: ");
var passwordPrompt = prompt("Enter your password: ");
function signIn(user, pass) {
if (user === database[0].username && pass === database[0].password) {
alert("Welcome" + database[0].username)
}
else {
alert("Wrong username or password!")
}
}
signIn(namePrompt, realNamePrompt)
Mmmm to access any, you would need to pass the index you want to access like this
function check(user, pass, index) {
if (user === database[index].username && pass === database[index].password) {
return user;
} return null;
}
then you could maybe do a loop, outside of this function to cover all the indexes, something like this:
for (int i = 0; i < USERS_LENGTH; i++) { const user = check (user, pass, i); if (user) return user; }
or a more functional approach with Array.find , something like this:
database.find(u => check(u))
ALTHOUGH, I don't think this is the correct approach to handle real database logins, this is brute force, and in a million records data base, this will take forever.
You can use find method on javascript (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find).
var database = [
{
username: "captain",
password: "america"
},
{
username: "bruce",
password: "banner"
},
{
username: "tony",
password: "stark"
}
];
function signIn(user, pass) {
const user= database.find((data) => data.username === user && data.password === pass);
if (user) {
alert("Welcome" + user.username)
}
else {
alert("Wrong username or password!")
}
}