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?
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?
Share Improve this question edited Jun 9, 2016 at 9:09 Pugazh 9,5615 gold badges36 silver badges56 bronze badges asked Jun 2, 2016 at 21:59 KaKoRoTKaKoRoT 331 gold badge1 silver badge5 bronze badges 5- 5 that's not json. That's plain old javascript. json is a text-encoded version of JS data structure for transport/transmittion. You have a regular JS data structure definition there. – Marc B Commented Jun 2, 2016 at 22:01
-
1
Depending on what result you want, the
some
,every
,find
andfindIndex
methods do that. – Bergi Commented Jun 2, 2016 at 22:02 -
FYI, you're paring a string to a DOM element. You probably wanted the
.value
of each of the elements, assuming they'reinput
s. If you want to stop the loop when a match is found, you can use abreak
statement. Andfor-in
isn't a great choice for Arrays in JS. – user1106925 Commented Jun 2, 2016 at 22:08 - Might loop over using userdata.users.forEach( ... ) instead. Also, lodash makes operations like these trivial. userdata.users is a collection (array of objects), and thus you could _.find(userdata.users, {'username': 'james', 'password': 'pass1'}) and if response is undefined, the user can't log in. – ryanm Commented Jun 2, 2016 at 22:08
- @marcB is it? damn what have i been learning all this time? what is the correct way of doing it to reflect JSON? – KaKoRoT Commented Jun 3, 2016 at 7:03
2 Answers
Reset to default 3Your loop is just fine; I suspect the true problem with your code, as @squint mentioned, is that you are paring 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 acplish 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("Wele " + 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("Wele " + 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("Wele " + 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>
Hey ran across this question while searching for an until
loop example in javascript... no luck there but I've tested a while
loop option on jsconsole that you may like
TLDR/One-Liner
var arr = ['first']; arr.push('second', 'third'); var i = 0; while (i < arr.length){ console.log(arr[i]); i++; };
Scriptlet version
#!/usr/bin/env node
// Assign first word/line/character into array type variable
var arr = ['first'];
// Push further values into array setup above
arr.push('second', 'third');
// Assign index for array to start point
var i = 0;
// Start while loop and continue while index value is less then array total length
while (i < arr.length){
// Present currently processed array indexed value
console.log(arr[i]);
// Place more processing lines here
// Add one to index variable for array before allowing loop to exit or parse the next index
i++;
};
// close while loop
In either of the above the output should be the same... looks like there's already plenty of examples for if
checks so pick the one ya like to throw in to above for testing around with.