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

Filter items with .filter .map .some .indexOf etc

本文关键字:过滤 项目 indexOf some filter map 使用      更新时间:2023-09-26

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

我希望它首先检查我的基础成分是否在配方成分数组中,然后在完成后过滤其余成分。因此,必须包括基础成分。

基础成分和选择的成分都在同一个成分数组(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}/>
            )
        } );