jayzee
jayzee

Reputation: 225

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

Upvotes: 0

Views: 58

Answers (2)

Muideen Adewale
Muideen Adewale

Reputation: 1

//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!!!!!');
        }
    }

Upvotes: 0

MTN
MTN

Reputation: 547

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"}]

Upvotes: 1

Related Questions