Filtering array with underscore.js

后端 未结 4 1933
囚心锁ツ
囚心锁ツ 2021-01-14 01:44

I am trying to filter some objects in my attempt to understand JS better and I\'m using underscore.js

I come from a C# background and am used to LINQ however undersc

4条回答
  •  耶瑟儿~
    2021-01-14 02:01

    I managed to get my solution all wrapped up into one filter call so thought I'd post it:

    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 = [];
    
          productsICanEat = _(products).filter(function (x) { return !x.containsNuts && !_(x.ingredients).any(function(y){return y === "mushrooms";});});
    
    
          expect(productsICanEat.length).toBe(1);
      });
    

提交回复
热议问题