You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 17:09:52