我有一个装满对象的食谱数组。一个对象看起来像这样
var recipes = [
{
name: 'All-Purpose Rub for Meat',
ingredients: [
{
name: 'white sugar',
quantity: {
number: 4,
unit: 'tablespoon'
},
},
{
name: 'salt',
quantity: {
number: 4,
unit: 'tablespoon'
}
},
{
name: 'paprika',
quantity: {
number: 1,
unit: 'tablespoon'
}
},
{
name: 'mustard powder',
quantity: {
number: 2,
unit: 'tablespoon'
}
},
{
name: 'ground black pepper',
quantity: {
number: .5,
unit: 'teaspoon'
}
},
{
name: 'dried oregano',
quantity: {
number: 1,
unit: 'pinch'
}
},
{
name: 'dried thyme',
quantity: {
number: 1,
unit: 'pinch'
}
},
],
servingSize: {
quantity: 12,
unit: 'servings'
},
// usedFor: [ribs, chicken, pork, fish, beef]
},
{
name: 'Rosemary Garlic Rub',
ingredients: [{
name: 'ground black pepper',
quantity: {number: 1, unit: 'tablespoon'}},
{
name: 'kosher salt',
quantity: {number: 1, unit: 'tablespoon'}},
{
name: 'chopped fresh rosemary',
quantity: {number: 3, unit: 'tablespoon'}},
{
name: 'dried rosemary',
quantity: {number: 1, unit: 'tablespoon'}},
{
name: 'diced garlic',
quantity: {number: 8, unit: 'cloves'}},
{
name: 'olive oil',
quantity: {number: .333, unit: 'cup'}}
],
servingSize: {quantity: 4, unit: 'servings'},
// usedFor: [chicken, pork]
},
]
我想做的是根据输入的香料过滤食谱数组,所以就像这样
filterRecipes({name:'黑胡椒粉'});
我尝试过
function filterRecipes(spice) {
let filteredarray = recipes.filter((recipe) => {
recipe.ingredients.includes(spice.name);
});
return filteredarray;
}
console.log(filterRecipes({name: 'kosher salt'}))
然后,filterRecipes函数将返回所有包含成分“黑胡椒粉”的配方的数组。
任何帮助将不胜感激。
似乎我需要与他相似的东西,但是我不能使用某些东西,因为我需要所有东西。我不知道为什么将下面的内容标记为正确的答案,但这并不能给我所有的帮助。带有配料的物品
Filtering array of objects by searching nested object properties
它应该返回一个配方数组,其中只包含具有作为参数放入的成分的对象
答案 0 :(得分:0)
includes()
在这里不是正确的选择,请尝试使用some()
来使用filterRecipes
函数:
function filterRecipes(recipes, ingredient) {
return recipes.filter(({ ingredients }) => {
return ingredients.some(({ name }) => name === ingredient);
});
}
...然后使用成分名称(而不是对象)来调用它:
filterRecipes(recipes, 'kosher salt');
您可以了解有关.some()
on MDN