Hello, I'm a beginner in Javascript and I am currently attempting to iterate over an array of JSON objects. However, I am facing issues with the code below that was designed to loop through a static array of JSON constants.
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 out all form fields!';
formErrorMessage.style.color = 'red';
event.preventDefault();
} else {
localStorage.setItem('userName', userName.value);
const allUsers = '[{"username":"test3","email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="60140513145320080f140d01090c4e030f0d">[email protected]</a>","password":"123"},{"username":"test2","email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c4b0a1b7b0f684acabb0a9a5ada8eaa7aba9">[email protected]</a>","password":"123123"},{"username":"test1","email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a3d7c6d0d792e3cbccd7cec2cacf8dc0ccce">[email protected]</a>","password":"456456456"}]';//JSON.parse(localStorage.getItem('users'));
for(var i = 0; i < allUsers.length; i++) {
var user = allUsers[i];
console.log(user.username);
if(user.username == userName) {
console.log('USERNAME FOUND!!!!!');
}
}
}
}
The goal is to determine whether a username exists within the user array. console.log(user.username); -> returns undefined and the .parse method also triggers an error.