使用 .filter .map .some .indexOf 等过滤项目
Filter items with .filter .map .some .indexOf etc
我正在 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}/>
)
} );
相关文章:
- 相对于角度控制器中的另一个阵列过滤阵列项目
- 限制在角度中过滤是否会阻止在 ng 重复中加载其他项目
- 观察角度过滤项目的变化
- 如何过滤推特流API订阅源,只获取与新闻相关的项目
- 使用 bxSlider 使用显示/隐藏过滤滑块项目
- jQuery在过滤后仅导航可见项目
- 角度按条件过滤数组中的多个项目
- 使用 .filter .map .some .indexOf 等过滤项目
- 角度.js分页过滤的数据并显示总项目,而无需在视图/控制器中复制代码
- Angular:过滤多个项目
- Jquery同位素过滤淡化不匹配的项目,而不是隐藏
- 使用同位素过滤后,当项目的宽度小于3时,请更改项目的宽度
- 使用下拉菜单反应过滤项目
- 用angular js过滤项目
- JavaScript | AngularJS:根据日期过滤结果过滤项目
- 过滤jQuery可排序的项目
- AppleScript JXA过滤表与许多行相同的名称,但不同的项目
- 我应该如何创建一个项目列表,过滤下拉项目选择在引导
- 我如何格式化谷歌图表数据,以显示项目的计数,但按年过滤
- 使用 jQuery (AJAX) 过滤项目 - 请求以错误的顺序完成