KaKoRoT KaKoRoT - 10 days ago 3
Javascript Question

How to loop through JSON array until condition is met?

just started learning JavaScript and trying to figure out the right way to iterate through an array to simulate a login process.

function validateLogin() {
var userdata = {
"users": [{
"username": "james",
"password": "pass1"
}, {
"username": "russel",
"password": "pass2"
}, {
"username": "jane",
"password": "pass3"
}, {
"username": "jeff",
"password": "pass4"
}]
};
var uname = document.getElementById("username");
var pword = document.getElementById("password");

var user = userdata.users;

for (var item in user) {
if (user[item].username == uname && user[item].password == pword) {
alert("Correct Username and Password")
} else {
alert("Incorrect Username or Password");
}
}
}


Problem is its storing all the data "user[item].username" when its meant to store one part of the array say [0] then check if "uname" and "pword" is the same if not carry on until it is and if not the authentication details are incorrect.

I'm sure am meant to do something like count = user[item].username; then count++ to the next iteration?

Either way I'm not getting it! can anyone help pls?

Answer

Your loop is just fine; I suspect the true problem with your code, as @squint mentioned, is that you are comparing strings to DOM elements rather than to the values (presumably) contained within those elements.

However, there are a couple of ways you could improve that loop of yours. First, you mention you do not want the loop to continue on if it has found what it is looking for. You can accomplish this with the break statement:

  for (var item in users) {
    if (users[item].username == uname && users[item].password == pword) {
      break;
    }
  }

Of course, that just gets you out of the loop, but doesn't record any information about HOW you got out of the loop. For that, you can consider initializing a variable to hold your user object, and referencing it outside the loop (note that here, I have saved userdata.users in a variable called users rather than user, since that sounds better and allows us to use user to store the actual individual user we're looking for):

  var users = userdata.users;
  var user;

  for (var item in users) {
    if (users[item].username == uname && users[item].password == pword) {
      user = users[item];
      break;
    }
  }

  if (user) {
    console.log("Welcome " + user.username);
  } else {
    console.log("Invalid username or password");
  }

Note also that the JavaScript for .. in statement in in many ways not the ideal way to iterate over Arrays. It would be better to use the brand-new for .. of statement if you can, and a good ol' for loop if not:

  var users = userdata.users;
  var user;

  for (var i = 0; i < users.length; i++) {
    if (users[i].username == uname && users[i].password == pword) {
      user = users[i];
      break;
    }
  }

  if (user) {
    console.log("Welcome " + user.username);
  } else {
    console.log("Invalid username or password");
  }

Finally, if you want to get really fancy and you are using ES6, the very latest stable version of JavaScript, you can use the brand-new Array.find method:

var user = userdata.users.find(function (user) {
  return user.username === uname && user.password === pword;
});

function validateLogin() {
  var userdata = {
    "users": [
      {"username": "james", "password": "pass1"},
      {"username": "russel", "password": "pass2"},
      {"username": "jane", "password": "pass3"},
      {"username": "jeff", "password": "pass4"}
    ]
  };

  var uname = document.getElementById("username").value;
  var pword = document.getElementById("password").value;

  var users = userdata.users;
  var user;

  for (var i = 0; i < users.length; i++) {
    if (users[i].username == uname && users[i].password == pword) {
      user = users[i];
      break;
    }
  }

  if (user) {
    console.log("Welcome " + user.username);
  } else {
    console.log("Invalid username or password");
  }

  return false;
}
<form onSubmit="validateLogin()">
  <input type="text" id="username" />
  <input type="password" id="password" />
  <input type="submit" />
</form>

Comments