使用underscore.js过滤数组 [英] Filtering array with underscore.js
问题描述
我试图过滤一些对象以更好地理解JS,并且使用了underscore.js
I am trying to filter some objects in my attempt to understand JS better and I'm using underscore.js
我来自C#背景,习惯于LINQ,但是下划线并不完全相同.
I come from a C# background and am used to LINQ however underscore is not quite the same.
您能帮我根据定义的测试筛选出此数组吗,我遇到的问题是数组上的array属性. Where
运算符与C#不同,这是我通常用来过滤项目的C#.
Can you help me filter out this array based on the defined test, the issue I'm having is the array property on the array. The Where
operator is diffeernt to C# which is what I'd normally use to filter items.
products = [
{ name: "Sonoma", ingredients: ["artichoke", "sundried tomatoes", "mushrooms"], containsNuts: false },
{ name: "Pizza Primavera", ingredients: ["roma", "sundried tomatoes", "goats cheese", "rosemary"], containsNuts: false },
{ name: "South Of The Border", ingredients: ["black beans", "jalapenos", "mushrooms"], containsNuts: false },
{ name: "Blue Moon", ingredients: ["blue cheese", "garlic", "walnuts"], containsNuts: true },
{ name: "Taste Of Athens", ingredients: ["spinach", "kalamata olives", "sesame seeds"], containsNuts: true }
];
it("given I'm allergic to nuts and hate mushrooms, it should find a pizza I can eat (functional)", function () {
var productsICanEat = [];
//This works but was hoping I could do the mushroom check as well in the same line
var noNuts = _(products).filter(function (x) { return !x.containsNuts;});
var noMushrooms = _(noNuts).reject(function(x){ return !_(x.ingredients).any(function(y){return y === "mushrooms";});});
console.log(noMushrooms);
var count = productsICanEat.length;
expect(productsICanEat.length).toBe(count);
});
推荐答案
您只需要从 reject
回调中删除!
,使其看起来像这样:
You just need to remove the !
from the reject
callback so that it look like this:
var noMushrooms = _(noNuts).reject(function(x){
return _(x.ingredients).any(function(y){return y === "mushrooms";});
});
否则,您将拒绝不包含蘑菇的蘑菇而不是包含蘑菇的蘑菇.
Otherwise you're rejecting the ones that don't contain mushrooms instead of those that do.
这篇关于使用underscore.js过滤数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!