我正在尝试筛选一些对象,以更好地理解JS,并使用underscore.js。
我来自C#背景,习惯于LINQ,但underscore并不完全相同。
您能帮助我根据定义的测试筛选出该数组吗?我遇到的问题是数组上的数组属性。 Where
运算符与C#不同,这通常是我用来过滤项目的。
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);
});
_.chain(list)
,然后就可以一整天地链式调用你的函数了 - 就像这样_.chain(myArray).filter(function(){ }).reject(function(){ })
http://underscorejs.org/#chaining - Thomas Jonesany
是some
的别名。 - JohnnyHK