Home > Blockchain >  How can i verify that a element is in my array?
How can i verify that a element is in my array?

Time:11-28

I'm making a simple login system for a school project and I need to verify if the usernames and passwords are in my list, but i can't seem to figure it out

var logs = [
    {
        username: "admin",
        senha: "admin"
    },

    {
        username: "client",
        senha: "client"
    }
]


function login_func() {
    let user =  document.getElementById('email_val')
    let passwd =  document.getElementById('passwd')

    if(logs.includes(user.value)){
        alert('amogus')
    }
    
}

If anyone could help I'd be really thankfull

CodePudding user response:

If you want the equivalent of includes but you need to check for a property of each object, use Array.some which takes a test function.

if (logs.some(obj => obj.username === user.value && obj.senha === passwd.value)) {

Of course, keep in mind that this type of 'authentication' will only serve for demonstration purposes and will never actually be useful for a real login.

CodePudding user response:

the best practice for this one will be the some prototype of an array:


    function isVerify(username, password){
    
        return logs.some(log => log.password === password && log.username === username)

    }

Of course, in the real world, you will encrypt passwords, and store them in DBs.

In case you want to return the logged-in user, use find instead:


    function login(username, password){
    
        return logs.find(log => log.password === password && log.username === username)

    }

This will return null in case of unmatch result.

CodePudding user response:

You can use find() method to find your user exists with your inputs.

const haveUser = (username, password) => !!logs.find(log => log.username == username && log.senha === password)

Important : When we wanna create an authentication system, should not create it on the Frontend side. It's completely wrong and risky because other developers open Dev Tools and can find your credentials.

  • Related