How to make a `where not` case?

I need, but with no . For example, I would like to find plays that do not have the name Shakespeare:

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

How can I do this using underscore ?

+6
source share
4 answers
 _.filter(listOfPlays, function(play) { return play.author !== 'Shakespeare' && play.year === 1611; }); 

http://underscorejs.org/#filter

where is nothing more than a convenient wrapper around the 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

+8
source

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

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

And then you can write your code as follows

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

Note. _.negate is available only from version 1.1. So, if you are using the previous version of _ , you can do something like this

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

Try the following:

 _.filter(listOfPlays,function(i){ return i['author']!='Shakespeare' && i['year']==1611; }); 
0
source

Lots of correct answers, but technically the OP just asked about the denial. You can also use garbage, in fact, this is the opposite of a filter. To achieve composite state 1611, not Shakespeare:

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

Source: https://habr.com/ru/post/976115/


All Articles