Opposite _.where (list, properties)

I have an array of objects and I set Selected = true for some clients. Using _.where , I get a new array that has only the selected clients. Is there any way to get clients that don't have this attribute? I do not want to set Selected = false for other clients and capture them

 _.where(customers, {Selected: false}); 

Thank you very much!

+4
source share
4 answers

use _.reject

 _.reject(customers, function(cust) { return cust.Selected; }); 

Docs: http://underscorejs.org/#reject

Returns values ​​in a list without elements that pass the truth test (iterator). The opposite of a filter.

Another option if you need this specific logic: you can also create your own Underscore Mixin using _.mixin and create the _.whereNot function and keep the nice _.where short syntax

+4
source

you could do it this way if you are sure that this property will not be:

 _.where(customers, {Selected: undefined}); 

this will not work if the object has Selected: false

You can also use _.filter , which is likely to be better:

 _.filter(customers, function(o) { return !o.Selected; }); 
+2
source

I don’t see the exact opposite, but you can just use filter , which allows you to specify the function as a predicate (or similarly, reject ):

 _.filter(customers, function(customer) { typeof customer.Selected == "undefined" }); 

Similarly, if you need a list of clients whose Selected is undefined or false:

 _.reject(customers, function(customer) { customer.Selected === true }); 
+2
source

Use the .filter method instead

 _.filter(customers, function(c) {return !c.Selected;}); 
+2
source

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


All Articles