'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":"[email protected]","password":"123"},{"username":"test2","email":"[email protected]","password":"123123"},{"username":"test1","email":"[email protected]","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.



Solution 1:[1]

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

const allUsers =  [{"username":"test3","email":"[email protected]","password":"123"},{"username":"test2","email":"[email protected]","password":"123123"},{"username":"test1","email":"[email protected]","password":"456456456"}]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 MTN