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

标签 javascript reactjs filtering ecmascript-6

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

我希望它首先检查我的 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>
  );
}

最佳答案

您需要下面这样的东西吗?此外,您之前在过滤器中缺少 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}/>
            )
        } );

关于javascript - 使用 .filter .map .some .indexOf 等过滤项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35612932/

相关文章:

javascript - 使用 Whammy Lib 将 blob 文件转换为 webm

javascript - 使用 imagemagick 将透明 PNG 转换为 JPEG

javascript - 标记上的传单 mouseout 事件

javascript - 如何禁用 Material UI Link API 组件

javascript > Kendo grid > 动态列过滤不起作用

matlab - 如何在空间和频域的每个尺度和方向上创建 64 个 Gabor 特征

javascript - 在 ko.applyBindings 中排除 html 元素

javascript - 如何将 this.state 传递给 react-routes?

django - 从 Django View 传递数据以使用react

mysql - mysql中基于用户权限的行过滤