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.