简体   繁体   中英

How do I check if an array includes an object with the same field in Javascript?

What is the best method to handle this? consider i'm handling a sign-up list database and i want to know whether a user the same username already exists or not?

something like this:

for (var i = 0; i < database.user.length; ++i) {
    if( database.user[i].username === username ) {
        return true;
    }
}
return false;

is there something better??

PS1: database.user is an array of objects

PS2: and I already know about the Array->indexOf func and it didn't help.

In javascript, any other way of doing this is just hiding the fact that, under the hood, they are just doing exactly what your code already does.

For example, you could filter your array, and check whether it's length is >= 1

var userExists = database.user.filter(u => u.username === username).length >= 1;

It's shorter, and arguably a little more readable than your original, but its not necessarily best, and neither is it likely to be faster.

Slightly better would be to use find - as this returns as soon as an element matches, meaning the whole array is not evaluated

var userExists = database.user.find(u => u.username === username) !== undefined;

( some would also be appropriate)


Note, this answer uses ES6 format for lambda expressions, the equivalent in unsupporting browsers would be

var userExists = database.user.filter(function(u) {return  u.username == username;}).length >= 1
// or
var userExists = database.user.find(function(u) {return  u.username == username;}) !== undefined;

Your code goes all the way the whole array even if an item at index 0 matches your query. You could use Array.prototype.some but even that one will fall short in performance compared to Array.prototype.findIndex . So my advice would be using findIndex.

database.user.findIndex(e => e.username === username) === -1 && login(username);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM