最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to make `where not` case? - Stack Overflow

programmeradmin0浏览0评论

I need where but with not case. For example, I would like to find plays, which have no name "Shakespeare":

_.where(listOfPlays, {author: !"Shakespeare", year: 1611});
                              ^^^^^^^^^^^^^
                            NOT Shakespeare

How can I do it with underscore?

I need where but with not case. For example, I would like to find plays, which have no name "Shakespeare":

_.where(listOfPlays, {author: !"Shakespeare", year: 1611});
                              ^^^^^^^^^^^^^
                            NOT Shakespeare

How can I do it with underscore?

Share Improve this question edited Oct 1, 2014 at 14:35 Huangism 16.4k7 gold badges50 silver badges75 bronze badges asked Oct 1, 2014 at 14:33 WarlockWarlock 7,47110 gold badges56 silver badges75 bronze badges
Add a comment  | 

4 Answers 4

Reset to default 11
_.filter(listOfPlays, function(play) {
    return play.author !== 'Shakespeare' && play.year === 1611;
});

http://underscorejs.org/#filter

where is nothing more than a convenient wrapper around filter:

// Convenience version of a common use case of `filter`: selecting only objects
// containing specific `key:value` pairs.
_.where = function(obj, attrs) {
    return _.filter(obj, _.matches(attrs));
};

https://github.com/jashkenas/underscore/blob/a6c404170d37aae4f499efb185d610e098d92e47/underscore.js#L249

You can cook your own "not where" version of _.where like this

_.mixin({
    "notWhere": function(obj, attrs) {
        return _.filter(obj, _.negate(_.matches(attrs)));
    }
});

And then you can write your code like this

_.chain(listOfPlays)
    .where({
        year: 1611
    })
    .notWhere({
        author: 'Shakespeare'
    })
    .value();

Note: _.negate is available only from v1.7.0. So, if you are using previous version of _, you might want to do something like this

_.mixin({
    "notWhere": function(obj, attrs) {
        var matcherFunction = _.matches(attrs);
        return _.filter(obj, function(currentObject) {
            return !matcherFunction(currentObject);
        });
    }
});

Plenty of right answers, but technically the OP just asked about negating. You can also use reject, it's essentially the opposite of filter. To achieve the compound condition of 1611 and not Shakespeare:

_.reject(_.filter(listOfPlays, function(play){
    return play.year === 1611
}), function(play) {
  return play.author === 'Shakespeare';
});

Try this:

_.filter(listOfPlays,function(i){
    return i['author']!='Shakespeare' && i['year']==1611;
});
发布评论

评论列表(0)

  1. 暂无评论