Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 whether or not the activeUser can be found 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 normal underscore way to do this? I have the following.

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

I'm using the findWhere method to either return an object or null if it doesn't exist.

like image 370
cusejuice Avatar asked Jan 25 '16 00:01

cusejuice


1 Answers

One alternative option would be to use the ._some() method. It will return a boolean based on whether anything was found:

var userExists = _.some(data.location.users, function (user) {
  return user.id === data.activeUser.id;
});
like image 121
Josh Crozier Avatar answered Oct 21 '22 04:10

Josh Crozier



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!