_.where(list, properties) 的相反操作是什么?

4

我有一个对象数组,我对一些客户设置了Selected = true。 使用_.where,我得到了一个新数组,其中只有已选客户。 是否有方法可以获取没有此属性的客户? 我不想将Selected = false设置为其余客户并通过它们抓取。

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

非常感谢!
4个回答

4

使用 _.reject 函数

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

文档:http://underscorejs.org/#reject

返回列表中未通过真值测试(迭代器)的元素。与filter相反。

如果您需要经常使用此特定逻辑,则可以使用另一种选项:使用_.mixin创建自己的Underscore Mixin,创建_.whereNot函数,并保持_.where的简洁语法。


2

如果您确定该属性不会存在,可以按照以下方式进行操作:

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

如果该对象具有 Selected: false,那么这将不起作用。

您还可以使用 _.filter,这可能会更好:

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

非常感谢!这么简单,我不知道你可以将未定义的参数传递。再次感谢。 - jimakos17

2

我认为没有严格的相反之说,但你可以很容易地使用filter,通过指定一个函数作为谓词(或类似的reject)实现:

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

同样地,如果您想要一个客户列表,其中Selected未定义或为false:

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

2
请使用.filter方法替代。
_.filter(customers, function(c) {return !c.Selected;});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接