[英]Filter array with objects based on another array
How do I filter such array:我如何过滤这样的数组:
const recipes = [
{
"id": 1,
"name": "Boiled Egg",
"ingredients": [
"egg",
"water"
],
},
{
"id": 2,
"name": "Pancakes",
"ingredients": [
"egg",
"milk",
"flour"
],
},
{
"id": 3,
"name": "Bread",
"ingredients": [
"flour",
"water",
"salt"
],
},
]
based on elements in such array基于此类数组中的元素
const selectedIngredients = ["milk", "salt"]
I played with combination of array.filter, array.some as show in Check if an array contains any element of another array in JavaScript but can't get it working properly我玩了 array.filter,array.some 的组合,如Check if an array contains any element of another array in JavaScript 中所示,但无法正常工作
I want to get recipes with id 2 and 3 as a result结果我想获得 id 为 2 和 3 的食谱
You can set the condition of the filter
to whether selectedIngredients
includes an item that is included in the item's ingredients
property:您可以将
filter
的条件设置为selectedIngredients
是否包含项目的ingredients
属性中包含的项目:
const recipes=[{id:1,name:"Boiled Egg",ingredients:["egg","water"]},{id:2,name:"Pancakes",ingredients:["egg","milk","flour"]},{id:3,name:"Bread",ingredients:["flour","water","salt"]}]; const selectedIngredients = ["milk", "salt"] const result =.selectedIngredients?length. [..:recipes]. recipes.filter(e => selectedIngredients.some(f => e.ingredients.includes(f))) console.log(result)
const recipes = [ { "id": 1, "name": "Boiled Egg", "ingredients": [ "egg", "water" ], }, { "id": 2, "name": "Pancakes", "ingredients": [ "egg", "milk", "flour" ], }, { "id": 3, "name": "Bread", "ingredients": [ "flour", "water", "salt" ], }, ] const selectedIngredients = ["flour", "water"] const selectAny = (list, filter) => list.filter(e => e.ingredients.some(i => filter.includes(i))); const selectAll = (list, filter) => list.filter(e => filter.every(i => e.ingredients.includes(i))); console.log('any', selectAny(recipes, selectedIngredients)); console.log('all', selectAll(recipes, selectedIngredients));
I would do it like this我会这样做
const recipes = [ { id: 1, name: 'Boiled Egg', ingredients: ['egg', 'water'], }, { id: 2, name: 'Pancakes', ingredients: ['egg', 'milk', 'flour'], }, { id: 3, name: 'Bread', ingredients: ['flour', 'water', 'salt'], }, ]; // const doRebuild = (selectedIngredients)=>{ const build = []; for(const two of selectedIngredients){ for(const one of recipes){ if(one.ingredients.some((a)=>two === a))build.push(one); } } return build.length > 0? build: ['No recipes']; }; // const content1 = doRebuild(['milk2', 'salt2']); const content2 = doRebuild(['milk', 'salt']); console.log(content1); console.log(content2);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.