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

Android中如何批量检查并显示API返回的非空strIngredient字段

批量处理API食材字段,仅显示非空内容

当然可行,完全不用逐个检查15个字段,通过动态拼接字段名+循环遍历的方式就能高效实现。以下是几种常用语言的具体实现:

JavaScript 示例

假设已获取API返回的餐品对象(从响应的meals[0]中提取):

const meal = response.meals[0];
const validIngredients = [];

// 遍历1到15的字段序号
for (let i = 1; i <= 15; i++) {
  const fieldName = `strIngredient${i}`;
  const ingredient = meal[fieldName];
  // 过滤空值、空字符串及纯空格内容
  if (ingredient && ingredient.trim() !== '') {
    validIngredients.push(ingredient);
  }
}

// 输出结果
console.log('有效食材列表:', validIngredients);

Python 示例

使用requests库获取API数据后处理:

import requests

# 获取API响应
resp = requests.get("https://www.themealdb.com/api/json/v1/1/lookup.php?i=52772")
meal_data = resp.json()['meals'][0]

valid_ingredients = []

# 循环生成字段名并检查
for num in range(1, 16):
    field_key = f"strIngredient{num}"
    ingredient = meal_data.get(field_key)
    # 过滤空内容
    if ingredient and ingredient.strip():
        valid_ingredients.append(ingredient)

print("有效食材列表:", valid_ingredients)

核心逻辑说明

  1. 动态拼接字段名:利用循环变量(1-15)拼接出strIngredient1到strIngredient15的字段名;
  2. 取值并过滤:通过拼接后的字段名获取对应值,判断是否为非空有效内容;
  3. 收集结果:将符合条件的食材存入列表,后续可直接用于展示。

这种方式不仅避免了重复代码,还能轻松适配字段数量变化(比如后续API调整为20个食材字段,只需修改循环范围即可)。

内容的提问来源于stack exchange,提问作者Dr.KeyOk

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 21:15:35