我正在用 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/