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

javascript - opposite of _.where(list, properties) - Stack Overflow

programmeradmin6浏览0评论

I have an array of objects and I set Selected = true to some customers. Using _.where I'm getting a new array which have only the selected customers. Is there any method to get the customers who don't have this attribute? I don't want to set Selected = false to the rest of the customers and grab them by

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

Thank you very much!

I have an array of objects and I set Selected = true to some customers. Using _.where I'm getting a new array which have only the selected customers. Is there any method to get the customers who don't have this attribute? I don't want to set Selected = false to the rest of the customers and grab them by

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

Thank you very much!

Share Improve this question edited May 3, 2013 at 21:31 BLSully 5,9391 gold badge29 silver badges46 bronze badges asked May 3, 2013 at 20:50 jimakos17jimakos17 9354 gold badges15 silver badges34 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 4

use _.reject

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

Docs: http://underscorejs/#reject

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

Another option if you need this particular logic a lot: You could also create your own Underscore Mixin with: _.mixin and create a _.whereNot function and keep the nice short syntax of _.where

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

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

this won't work if the object has Selected: false

You could also use _.filter which would probably be better:

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

I don't there's an opposite exactly, but you could easily just use filter, which lets you specify a function as the predicate (or similarly, reject):

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

Similarly if you wanted a list of customers whose Selected is undefined or false:

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

Use .filter method instead

_.filter(customers, function(c) {return !c.Selected;});
发布评论

评论列表(0)

  1. 暂无评论