Use underscore to return true or false with findWhere

Let's say I have the following data:

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

I want to return a boolean, is it possible to find activeUser in the data.location.users array. Note that the objects in the location.users array will NOT have the same keys as the activeUser object.

Is there a common way to emphasize? I have the following.

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

I use the findWhere method to return an object or null if it does not exist.

+6
source share
1 answer

One alternative is to use the ._some() method. It will return a boolean based on the discovery of something:

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

All Articles