简体   繁体   中英

Loop over an array of json objects in JAVASCRIPT

I'm new to Javascript, and I'm trying to loop over an array of JSON [{},{},{}, ...]

I have created this function to loop on a static Array of JSON constant, but it's not working properly even after checking online and trying.

function saveAccount() {
    const userName = document.getElementById('user_name');
    const userPassword = document.getElementById('user_password');
    const formErrorMessage = document.getElementById('fillFormError');
    
    if(userName.value == '' || userPassword.value == '')
    {
        formErrorMessage.textContent = 'Please fill the form fields first!';
        formErrorMessage.style.color = 'red';
        event.preventDefault();
    }
    else
    {
        localStorage.setItem('userName', userName.value);
        const allUsers =  '[{"username":"test3","email":"test3@hotmail.com","password":"123"},{"username":"test2","email":"test2@hotmail.com","password":"123123"},{"username":"test1","email":"test1@hotmail.com","password":"456456456"}]';//JSON.parse(localStorage.getItem('users'));
        for(var i = 0; i < allUsers.length; i++){
            var user = allUsers[i];
            console.log(user.username);
            //alert(user["username"])
            if(user.username == userName){
                console.log('USERNAME FOUND!!!!!');
            }
        }

    }

}

the purpose is to find if the username exists in my array of users. console.log(user.username); -> return undifined and the .parse also returns an error.

allUser is currently defined as a string, which you can't loop over. Try this:

const allUsers =  [{"username":"test3","email":"test3@hotmail.com","password":"123"},{"username":"test2","email":"test2@hotmail.com","password":"123123"},{"username":"test1","email":"test1@hotmail.com","password":"456456456"}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM