I am making a login site via JSON, and I want to check if a username matches with a password (by using array indexes to match username, password and email) but I can't figure out how to see if the username matches with any index number and if there is an index in an array that corresponds with it in the passwords section. I can use indexOf with recursion (function that calls itself) but I have to increment the index checked by 1 which I do not know how to do. (searched for any stuff but I can't find anything) like this:
{
"usernames": [
"Supa", "Marwan", "Jason", "Jacob",
]
"passwords": [
"placeholder", "placeholder1", "placeholder2", "placeholder3",
]
}
function checkDetails(username, password) {
let message = document.getElementById("placeholder");
let password = document.getElementById("placeholder1");
let username = document.getElementById("placeholder2");
//part I am struggling with
let usernames = json.parse("usernames");
let passwords = json.parse("passwords");
message.innerHTML = (username === usernames[/*i want this to increment to check*/]) ?
message.innerHTML = (password === indexOf(/*I want this to be the index of the one
index that IS true to the conditional above*/)) ? m
essage.innerHTML = "Success with logging in" :
message.innerHTML = "Invalid username or password";
As comments attest, your JSON was malformed and this is a completely insecure way of managing a login. That said, here's how you can test for a username, and if it exists, check to see if the appropriate password checks out. In the first line of the function, we normalize the username to be lowercase with any extra space removed.
let json = {
"usernames": [
"Supa", "Marwan", "Jason", "Jacob",
],
"passwords": [
"placeholder", "placeholder1", "placeholder2", "placeholder3",
]
}
function checkDetails(username, password) {
let userindex = json.usernames.findIndex(u => u.toLowerCase().trim() === username.toLowerCase().trim());
if (userindex === -1) {
return 'username does not exist';
} else if (json.passwords[userindex] !== password) {
return 'wrong password';
}
return 'success!'
}
console.log(checkDetails('Supa1', 'placeholder1'))
console.log(checkDetails('Supa', 'placeholder1'))
console.log(checkDetails('Supa', 'placeholder'))