React中多键过滤数组并拼接食材与分量的实现方法
解决食材与对应分量的配对拼接问题
你的问题出在把食材和分量分开收集后,无法通过索引对应配对——Object.keys返回的键顺序是先所有strIngredient开头的键,再所有strMeasure开头的键,导致过滤后的数组里食材和分量是分开的两组,自然没法直接拼接。
正确的思路是按数字索引配对食材和分量:因为strIngredientN和strMeasureN是一一对应的,所以直接遍历索引数字,同时获取对应位置的食材和分量,再做过滤和拼接。
实现方案1:for循环(直观易读)
const validIngredients = []; // 遍历1到6(对应API返回的最大索引) for (let i = 1; i <= 6; i++) { const ingredientKey = `strIngredient${i}`; const measureKey = `strMeasure${i}`; const ingredient = singleRecipe[ingredientKey]; const measure = singleRecipe[measureKey]; // 只保留食材非空的项,分量为空时可替换为"适量"或留空 if (ingredient) { validIngredients.push(`${ingredient} - ${measure || '适量'}`); } }
实现方案2:Array.from(简洁写法)
const validIngredients = Array.from({ length: 6 }, (_, index) => { const idx = index + 1; // 转换为1开始的索引 const ingredient = singleRecipe[`strIngredient${idx}`]; const measure = singleRecipe[`strMeasure${idx}`]; // 食材非空则返回拼接字符串,否则返回null后续过滤 return ingredient ? `${ingredient} - ${measure || ''}` : null; }).filter(Boolean); // 过滤掉null项
补充说明
如果API返回的食材数量不固定(比如可能超过6个),可以先找出所有strIngredient开头的键,提取最大索引值,再循环到该最大值,避免硬编码6:
// 动态获取最大食材索引 const maxIndex = Math.max( ...Object.keys(singleRecipe) .filter(key => key.startsWith('strIngredient')) .map(key => parseInt(key.replace('strIngredient', ''), 10)) ); // 后续循环改为从1到maxIndex即可
内容的提问来源于stack exchange,提问作者ganga
相关产品推荐
相关产品推荐

