javascript - Use underscore to return true or false with findWhere - Stack Overflow

Let's say I have the following data:var data = {activeUser: { id: 3, name: 'Joe', someth

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.

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.

Share Improve this question edited Jan 25, 2016 at 0:47 Josh Crozier 242k56 gold badges400 silver badges313 bronze badges asked Jan 25, 2016 at 0:07 cusejuicecusejuice 10.7k27 gold badges95 silver badges150 bronze badges 1
  • stackoverflow./questions/143847/… – ClearBoth Commented Jan 25, 2016 at 0:10
Add a ment  | 

1 Answer 1

Reset to default 6

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;
});

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745353543a4623983.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信