JavaScript硬编码API JSON属性问题:如何移除值为null的strMeasure与strIngredient属性
解决CocktailDB API中null配料/计量属性的渲染问题
嘿,我完全懂你现在的困扰——硬编码这些带数字后缀的属性不仅重复繁琐,还会把null值直接渲染到页面上,看起来乱糟糟的。咱们不用一个个写死strMeasureX和strIngredientX,而是用动态逻辑过滤掉无效值,再生成列表项。
核心思路拆解(以strMeasure7和strIngredient7为例)
先拿你提到的第7组属性来说明逻辑:我们需要先判断strIngredient7是否为null(因为配料是核心,计量可能为空但配料存在),如果有效,再把计量和配料组合起来;如果无效,直接跳过不渲染。
示例代码片段:
// 针对单份饮品,提取第7组配料的逻辑 const drink = data.drinks[0]; // 取第一杯玛格丽特为例 const ingredient7 = drink.strIngredient7; const measure7 = drink.strMeasure7; let ingredientItem = ''; if (ingredient7 !== null) { // 计量存在就拼接,不存在只显示配料名称 ingredientItem = `<li>${measure7 ? `${measure7} ` : ''}${ingredient7}</li>`; } // 只有当这个条目有效时,才添加到页面 if (ingredientItem) { // 这里可以把它插入到ul中 }
扩展到所有配料的完整解决方案
把上面的逻辑封装成一个函数,遍历所有可能的配料组(API最多支持到15组左右),自动过滤掉null值,再动态生成列表:
修改后的完整代码:
const url = "https://www.thecocktaildb.com/api/json/v1/1/search.php?s=margarita"; const list = document.querySelector(".results"); // 封装提取有效配料的函数 function getValidIngredients(drink) { const ingredients = []; // 遍历1到15,覆盖API可能返回的所有配料组 for (let i = 1; i <= 15; i++) { const ingredientKey = `strIngredient${i}`; const measureKey = `strMeasure${i}`; const ingredient = drink[ingredientKey]; const measure = drink[measureKey]; // 只有配料存在时才加入数组 if (ingredient !== null) { ingredients.push({ measure: measure || '', name: ingredient }); } } return ingredients; } async function getMargaritas() { try { const response = await fetch(url); const data = await response.json(); data.drinks.forEach(drink => { // 获取当前饮品的有效配料列表 const validIngredients = getValidIngredients(drink); // 把配料数组转成li字符串 const ingredientList = validIngredients.map(item => `<li>${item.measure ? `${item.measure} ` : ''}${item.name}</li>` ).join(''); // 渲染单份饮品的HTML list.innerHTML += `<div class="result"> <h1>${drink.strDrink}</h1> <ul>${ingredientList}</ul> </div>`; }); } catch (error) { list.innerHTML = theError("Whoops, sorry! No drink for you this time.. Better luck next time 😉"); } } getMargaritas(); function theError(message = "Error") { return `<div class="error">${message}</div>`; }
为什么原来的代码会失败?
你之前的写法是直接硬编码所有7个列表项,不管对应的属性是不是null——当strMeasureX或strIngredientX为null时,页面上会直接显示null或者空的列表项。而动态过滤的方式会跳过所有无效的属性,只渲染有值的配料。
这样修改后,不仅解决了null值的问题,代码也更简洁灵活,哪怕API返回更多配料组也能自动处理~
内容的提问来源于stack exchange,提问作者Luna
相关产品推荐
相关产品推荐

