基于宏量营养素含量的USDA API食物检索问题(JavaScript)
解决USDA API提取指定营养素数据的问题
嘿,我来帮你搞定这个提取蛋白质、碳水化合物和脂肪数据的需求!既然你已经明确是要从API返回的JSON里提取信息而不是过滤结果,那我们可以直接针对返回的结构来处理:
第一步:先明确USDA营养素编码对应关系
你请求里的三个营养素ID对应:
203:蛋白质(Protein)204:脂肪(Total lipid (fat))205:碳水化合物(Carbohydrate, by difference)
第二步:编写提取逻辑
我们可以写一个小辅助函数,用来从单个食物的营养素列表里快速拿到指定ID的数值,然后在AJAX回调里遍历所有食物,提取你需要的信息。
修改后的jQuery AJAX代码
// 辅助函数:根据营养素ID提取对应数值 function getNutrientValue(nutrientsArray, nutrientId) { const nutrient = nutrientsArray.find(n => n.nutrient_id === nutrientId); // 如果找不到对应营养素,返回0或者null,根据你的需求调整 return nutrient ? parseFloat(nutrient.value) : 0; } $.ajax({ type: "GET", async: true, // 强烈建议改成异步,同步请求会阻塞页面 url: "http://api.nal.usda.gov/ndb/nutrients/?format=json&api_key=your_api_key&nutrients=205&nutrients=204&nutrients=203", success: function(response) { // 检查返回结构是否正确 if (response && response.report && response.report.foods) { // 提取整理后的食物数据数组 const processedFoods = response.report.foods.map(food => { return { name: food.name, protein: getNutrientValue(food.nutrients, "203"), // 蛋白质含量(g) fat: getNutrientValue(food.nutrients, "204"), // 脂肪含量(g) carbs: getNutrientValue(food.nutrients, "205") // 碳水化合物含量(g) }; }); // 现在你可以用processedFoods做任何你想做的事,比如打印或者渲染到页面 console.log("提取后的食物数据:", processedFoods); // 如果后续需要筛选符合特定含量的食物(比如蛋白≥20g,碳水≥40g,脂肪≤10g),可以加过滤逻辑 const filteredFoods = processedFoods.filter(food => { return food.protein >= 20 && food.carbs >= 40 && food.fat <= 10; }); console.log("符合含量要求的食物:", filteredFoods); } else { console.error("API返回结构异常,请检查请求参数"); } }, error: function(xhr, status, error) { console.error("请求USDA API失败:", error); } });
几个注意点:
- 把
your_api_key替换成你自己的USDA API密钥 - 我把
async: false改成了async: true,同步AJAX会导致页面卡顿,实际项目里尽量用异步 - 辅助函数里用了
find方法,如果你需要兼容旧浏览器,可以换成for循环遍历 - 如果API返回的数值有非数字情况,
parseFloat会处理成NaN,你可以根据需求添加额外的容错逻辑
内容的提问来源于stack exchange,提问作者Jsmooth
相关产品推荐
相关产品推荐

