I\'m trying to perform a filter() operation in JavaScript. I have the following
ID: 3783623 • Letter: I
Question
I'm trying to perform a filter() operation in JavaScript. I have the following JSON object:
const recipes = [{
name: "peanut butter cups",
ingredients: [
{name: 'chocolate', calories: 300},
{name: 'butter', calories: 500},
{name: 'milk', calories: 150},
{name: 'peanut butter', calories: 450}
]
},{
name: "pizza",
ingredients: [
{name: 'flour', calories: 300},
{name: 'milk', calories: 100},
{name: 'eggs', calories: 200},
{name: 'tomato paste', calories: 200},
{name: 'cheese', calories: 500}
]
},{
name: "dessert pizza",
ingredients: [
{name: 'flour', calories: 300},
{name: 'milk', calories: 100},
{name: 'eggs', calories: 200},
{name: 'chocolate', calories: 300},
{name: 'marshmellos', calories: 320},
{name: 'butter', calories: 500},
]
}];
And, if I just want recipes that contain chocolate, I do the following:
var chocolateRecipes = recipes.filter(function (recipe) {
return recipe.ingredients.filter(function (ingredient) {
return ingredient.name === 'chocolate';
}).length;
});
How would perform this same filter if the ingredients didn't have the property "name: " and no calorie property AT ALL? For example, instead of
const recipes = [{
name: "peanut butter cups",
ingredients: [
{name: 'chocolate', calories: 300},
{name: 'butter', calories: 500},
...
what if the object looked like the following:
const recipes = [{
name: "peanut butter cups",
ingredients: ['butter', 'chocolate'],
...
I can't do ingredient.name anymore because "name: " is no longer present. How would I do this? Thanks.
Explanation / Answer
Yeah you can use traditional indexing method that are popular in C and C++ i.e., like ingredients[0] === 'butter' or
ingredients[1] === 'chocolate'.
Hope it helps.