【问题标题】:Filter items with .filter .map .some .indexOf etc使用 .filter .map .some .indexOf 等过滤项目
【发布时间】:2016-06-07 09:06:01
【问题描述】:

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

我希望它首先检查我的 Baseingredient 是否在 recipe-in​​gredient 数组中,然后在完成后过滤其余部分。所以基础成分必须包含在内。

baseingredient 和选择的成分都在同一个成分数组(cartIds)中,所以“cartIds”还包括我 currentBaseingredient 的 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>
  );
}

【问题讨论】:

  • 你没有问问题。
  • 对不起,我的问题是,我怎样才能将我的基础成分包含在过滤器函数中? @zerkms
  • @CeciliaFredriksson:只是测试一下?你到底遇到了什么问题?

标签: javascript reactjs filtering ecmascript-6


【解决方案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}/>
            )
        } );

【讨论】:

  • 我没有完全理解你的问题,但似乎你肯定希望包含 baseIngredient,所以使用 filter 和 && 来构建你的谓词
  • 我想展示所有包含基础成分和其他成分的食谱。 =)
  • 酷,那么上面的方法不适合你吗?我意识到我最初打错了字,输入的是“include”而不是“includes”
  • 呵呵是的,我也注意到了,但它似乎不起作用:/现在它没有显示我的任何食谱:P
猜你喜欢
  • 2019-06-12
  • 2020-12-11
  • 1970-01-01
  • 1970-01-01
  • 2018-06-07
  • 1970-01-01
  • 1970-01-01
  • 2018-12-23
  • 2019-01-21
相关资源
最近更新 更多