gpt4 book ai didi

javascript - 使用 underscore.js 过滤数组

转载 作者:搜寻专家 更新时间:2023-11-01 04:44:24 25 4
gpt4 key购买 nike

我正在尝试过滤一些对象以更好地理解 JS,并且我正在使用 underscore.js

我有 C# 背景,习惯了 LINQ,但下划线不太一样。

你能帮我根据定义的测试过滤掉这个数组吗,我遇到的问题是数组的数组属性。 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);
});

最佳答案

您只需从 reject 回调中删除 ! ,使其看起来像这样:

var noMushrooms = _(noNuts).reject(function(x){ 
return _(x.ingredients).any(function(y){return y === "mushrooms";});
});

否则,您将拒绝那些含有蘑菇的,而不是那些含有蘑菇的。

关于javascript - 使用 underscore.js 过滤数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14339523/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com