there are an array and var I created:
var database = [
{
username:"candy",
password:"666"
},
{
username: "abby",
password: "123"
},
{
username: "bob",
password: "777"
}
];
var newsFeed = [
{
username: "Bob",
timeline: "So tired from all that learning!"
},
{
username: "Midori",
timeline: "Javascript is sooooo cool!"
},
{
username: "Abby",
timeline: "Javascript is preeetyy cool!"
}
]
var usernamePrompt = prompt("What\'s your username?");
var passwordPrompt = prompt("What\'s your password?");
and I want to use forEach to go through all array value from var database and then check them whether true or false
here is rest of the code:
database.forEach(checkDatabase2);//using forEach
function checkDatabase2(username,password) {
if (username === database.username && password === database.password){
return true;
}
return false;
and finally to check if it's true then print newsFeed, eles it will have alert, here is what I do:
function signIn(username,password) {
if (checkDatabase2(username,password)===true){
console.log(newsFeed);
}else{
alert("Opps! Worng Password!");
}
}
signIn(usernamePrompt,passwordPrompt);
But when I enter the value whatever I put, it always comes to alert("Opps! Worng Password!"); How I can fix it when I put the correct value from database =[], it will return true??
One option you have is to use some to check if atleast one element of array element is the username and password
var database = [{"username":"candy","password":"666"},{"username":"abby","password":"123"},{"username":"bob","password":"777"}];
function checkDatabase2(username, password) {
return database.some(o => o.username == username && o.password == password);
}
console.log(checkDatabase2("bob", "777"));
console.log(checkDatabase2("bob", "NOT777"));
Don't use forEach, use some.
function validate (username, password) {
return database.some(function(item) {
return (item.username === username && item.password === password);
});
}
function checkDatabase2 (username, password) {
if (validate(username, password)) {
return true;
}
return false;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With