0

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 undefined and the .parse also returns an error.

1
  • Why don't you parse the string? If it is parsed in your real code, try logging user and see what it gives. Commented May 23, 2022 at 11:13

2 Answers 2

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"}]
Sign up to request clarification or add additional context in comments.

Comments

0
//Make allUsers an iterable by using JSON.parse e.g:

   var iterableAllUsers = JSON.parse(allUsers);
   for(var i = 0; i < iterableAllUsers.length; i++){
        if(iterableAllUsers[i].username == userName){
            console.log('USERNAME FOUND!!!!!');
        }
    }

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.