问题描述
Array.forEach((element) => {
recipes.forEach((curr,index) => {
found = true;
item = element;
if (!curr.ingredients.includes(element)) found = false;
if (index + 1 === recipes.length && found === false) {
console.log(element,false);
} else if (index + 1 === recipes.length && found === true) {
console.log(element,true);
foundItem = element;
}
});
});
return foundItem;
大家好...我正在尝试调试这样的代码...正在发生的事情是,如下图所示,我的代码正在返回“açúcar”、“calabresa”和“ cerveja”。 Image where you can see the output from my console
然而,这不是我的意思,因为我正在遍历一个 JSON 列表,该列表恰好包含几种不同食谱的成分...... 如下
"recipes": [
{
"id": "00832498-3acc-4bde-9d89-77eacef26680","title": "Excelente pudim de milho","ingredients": [
"abóbora","aveia","azeite","açúcar","cerveja","frango","milho","morango","vinho"
],"price": 78.53
},{
"id": "008b345d-8f7c-427d-988b-4f238b8315f2","title": "Excelente bolo de azeite","price": 82.55
},{
"id": "00d14194-f223-447e-86a0-b535c451d53f","title": "Exuberante coxinha de vinho","calabresa","chuchu","uva",
我想要的是 açucar,因为它是所有食谱中唯一存在的成分... 至于我,这里似乎存在某种与缓存相关的问题
解决方法
也许你可以把你的代码改成这样:
Array.forEach((element) => {
const isIncluded = recipes.every(recipe => recipe.ingredients.includes(element));
if (isIncluded) {
// Do something with the ingredient or the element.
}
});
return foundItem;
every 方法检查每个食谱是否包含您传递给它的成分。
,如果你可以访问 lodash,你可以让它变得非常干净
import { intersection } from 'lodash'
getCommonIngredients = (recipes) => {
const ingredients = recipes.map(recipe => recipe.ingredients)
return intersection(...ingredients)
}