使用.filter .map .some .indexOf等过滤项目

时间:2016-02-24 20:56:53

标签: javascript reactjs filtering ecmascript-6

我在react.js和es6中构建食谱生成器。 我试图以一种好的方式过滤食谱,现在我只是检查我的食谱是否包含任何选择的成分。

我希望首先检查我的Baseingredient是否在配方成分数组中,然后在完成后过滤其余部分。所以必须包括baseingredient MUST

baseingredient和选择的成分都在相同的成分阵列(cartIds),所以" cartIds"还包括我当前的基础代码的Id。

这就是我今天的代码。

const recipes = () => {
  return { recipes: Store.getRecipes(), cart: Store.getCart(), baseingredient: Store.getCurrentBaseIngredient() }
}

const Recipes = ( props ) => {
  var cartIds = props.cart.map(item => item.ingredientId); // Ex: [11, 23, 1]

  // TODO: this ingredient-id must be in the recipes ingredient array!!
  var baseIngredient = props.baseingredient.ingredientId;
  console.log('baseingredient id:',baseIngredient); // Ex: 1

  var recipes = props.recipes
    .filter(recipe => ( // Run filter function on all recipes
      recipe.ingredients.some(ingredient => ( // Check if reciepe contains any of the chosen ingredients
        cartIds.indexOf(ingredient.ingredientId) >= 0) // Ingredient check
      )
    )) // Now we have a list of reciepes which contain some of the chosen ingredients
    .map( ( recipes, i ) => {
      return (
        <RecipesItem
          key={i}
          recipe={recipes}/>
        )
    } );
  return (
    <div>
      <table className="table table-hover">
        <thead>
          <tr>
            <th>Recipe</th>
            <th>Description</th>
          </tr>
        </thead>
        <tbody>
          {recipes}
        </tbody>
      </table>
    </div>
  );
}

1 个答案:

答案 0 :(得分:1)

下面是你需要的东西吗?此外,您在

之前错过了过滤器中的return关键字
var recipes = props.recipes
          .filter(recipe => ( // Run filter function on all recipes
              return recipe.ingredients.includes(baseIngredient) && recipe.ingredients.some(ingredient => ( // Check if reciepe contains any of the chosen ingredients
                cartIds.indexOf(ingredient.ingredientId) >= 0) // Ingredient check
              )
            ))  // Now we have a list of reciepes which contain some of the chosen ingredients
        .map( ( recipes, i ) => {
          return (
            <RecipesItem
              key={i}
              recipe={recipes}/>
            )
        } );