2016-01-25 9 views
6

Diciamo che ho i seguenti dati:Usa sottolineano a restituire true o false con findWhere

var data = { 
    activeUser: { id: 3, name: 'Joe', something: 'else' }, 
    location: { 
     users: [{id: 1}, {id: 2}, {id: 3}] 
    } 
}; 

Voglio tornare un valore booleano se il activeUser può essere trovato nella matrice data.location.users. Notare che gli oggetti nell'array location.users NON avranno gli stessi tasti dell'oggetto activeUser.

Esiste un normale metodo di sottolineatura per eseguire questa operazione? Ho il seguente

var userExists = (_.findWhere(data.location.users, {id: data.activeUser.id})) ? true : false; 

sto usando il metodo findWhere a uno restituire un oggetto o null se non esiste.

+0

http://stackoverflow.com/questions/143847/best-way-to-find-if-an-item-is-in-a- javascript-array – ClearBoth

risposta

6

Un'opzione alternativa sarebbe utilizzare ._some() method. Si restituirà un valore booleano in base a se qualcosa è stato trovato:

var userExists = _.some(data.location.users, function (user) { 
    return user.id === data.activeUser.id; 
}); 
Problemi correlati