Jon*_*Jon 4 javascript underscore.js
我试图过滤一些对象,试图更好地理解JS,我正在使用underscore.js
我来自C#背景并习惯LINQ但是下划线并不完全相同.
你能帮我根据定义的测试过滤掉这个数组,我遇到的问题是数组上的数组属性.该Where运营商diffeernt到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);
});
Run Code Online (Sandbox Code Playgroud)
Joh*_*yHK 10
您只需!要从reject回调中删除它,使它看起来像这样:
var noMushrooms = _(noNuts).reject(function(x){
return _(x.ingredients).any(function(y){return y === "mushrooms";});
});
Run Code Online (Sandbox Code Playgroud)
否则,你拒绝了那些不含有蘑菇,而不是那些做.
更简洁的方法是使用下划线的chain()函数:
var noMushrooms = _(products).chain()
.filter(function (x) {
return !x.containsNuts;})
.reject(function(x){
return _(x.ingredients).any(function(y){
return y === "mushrooms";
});
})
.value();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
22766 次 |
| 最近记录: |