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

如何在React中遍历JSON数组对象,筛选键名含strIngredient的属性值

你可以在组件内实现showIngredientsList方法,逻辑是遍历饮品对象的所有键,筛选出键名包含strIngredient且值不为空的项,再循环渲染即可。

修改后的完整代码如下:

import React from "react";

function Drinks({ drinkList }) {
  if (!drinkList) return <></>;
  const drink = drinkList.drinks[0];

  const showIngredientsList = () => {
    // 遍历对象所有键,筛选符合要求的项
    const ingredients = Object.keys(drink)
      .filter(key => key.includes('strIngredient') && drink[key])
      .map(key => <li key={key}>{drink[key]}</li>);
    return ingredients;
  };

  return (
    <section className="drinkCard">
      <h1 className="drinks-name">{drink.strDrink}</h1>
      <img src={drink.strDrinkThumb} alt="Drink" />
      <p>
        <strong>类别:</strong>
        {drink.strCategory}
      </p>
      <p>
        <strong>是否含酒精:</strong>
        {drink.strAlcoholic}
      </p>
      <p>
        <strong>制作说明:</strong>
        {drink.strInstructions}
      </p>
      <ol>{showIngredientsList()}</ol>
    </section>
  );
}

export default Drinks;

代码说明:

  • 把重复调用的drinkList.drinks[0]提取成单独变量,简化代码结构
  • Object.keys(drink)可以拿到该对象所有键名组成的数组
  • filter方法里同时做两个判断:键名包含strIngredient、对应的值存在(过滤掉API返回的空配料项)
  • 最后把过滤后的配料值映射为li元素返回即可

内容的提问来源于stack exchange,提问作者mw3981

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 08:45:07