0

I have this code:

    var users = [];
users.push({
    username: "admin",
    password: "admin"
});
this.showAllUsers = function() {
    console.log(users);
};
this.addUser = function(user) {
    if('username' in user && 'password' in user) {
        users.push({
            username: user.username,
            password: user.password
        })
    }
    else {
        throw "Invalid object";
    }
};
this.isExist = function(user) {
    console.log(users.indexOf({
        username: "admin",
        password: "admin"
    }));

};

Why console log prints all the time -1 ? Users array contains array with object with property username: "admin: and password: "admin".

Artur Kasperek
  • 565
  • 2
  • 5
  • 17
  • 6
    Just a note - if you're intending to put passwords in some client side code, you may want to rethink what you're doing. – James Thorpe Sep 08 '15 at 16:23
  • You need to loop and check each property. – epascarello Sep 08 '15 at 16:24
  • you can't simply check object equality in javascript. http://stackoverflow.com/questions/201183/how-to-determine-equality-for-two-javascript-objects – Lee Sep 08 '15 at 16:25

3 Answers3

1

The indexOf method uses strict equals (===). When you use {foo: bar}, you create a new (unique) object that will not evaluate strictly equal to anything already in the array.

What you should do is iterate through the array and use a function to compare each object using deep equality. Simply, you could use something like:

function match(arr, ref) { // Take an array and a reference object
  return arr.filter(function (cur) { // Select any items in the array...
    return Object.keys(ref).every(function (key) { // Where all keys...
      return ref[key] === cur[key]; // Have the same value in the item and reference
    });
  });
}
ssube
  • 47,010
  • 7
  • 103
  • 140
0

Take a look here indexOf.
And remember that managing passwords on the client side is security flaw.

Evil
  • 460
  • 1
  • 11
  • 25
0
this.isExist = function(user) {
    console.log(users.indexOf({
        username: "admin",
        password: "admin"
    }));
};

The problem here is that you're checking if the users array contains this new object you're creating. Since it's a new object, it's obviously not going to contain it. You need to check to see if the users object contains any object that has a username or password equal to "admin". Maybe something like

this.isExist = function(user) {
    for(var x = 0; x < users.length; x++) {
        var current = users[x];
        if(current.username === user.username && current.password === user.password) {
            return true;
        }
    }

    return false;
};

Or, alternatively, you can simply use Linq.js, which helps a lot with these kind of queries. It's one of my favorite libraries.

https://linqjs.codeplex.com/

Carlos Rodriguez
  • 2,190
  • 2
  • 18
  • 29