如何过滤thecocktaildb API返回JSON的相似属性并提取食材
处理TheCocktailDB API中的食材属性生成非空有序数组
嘿,这事儿不难!我经常处理这类API返回的结构化数据,给你两种实用的实现方式,保证能生成你想要的strIngredients数组:
方法一:传统循环(直观可控)
这种方式逻辑清晰,适合新手理解,也能确保严格按照strIngredient1到strIngredient15的顺序收集食材:
// 假设你从API拿到的单份饮品数据存在drink变量里 const drink = { strIngredient1: "Lager", strIngredient2: "Tequila", strIngredient3: "", strIngredient4: "Lime Juice", // ... 剩下的strIngredient5到15属性 strIngredient15: "" }; const strIngredients = []; // 遍历1到15的食材序号 for (let i = 1; i <= 15; i++) { // 动态拼接属性名获取食材值 const ingredient = drink[`strIngredient${i}`]; // 过滤空值和纯空格的情况 if (ingredient && ingredient.trim() !== "") { strIngredients.push(ingredient.trim()); } } console.log(strIngredients); // 输出结果:["Lager", "Tequila", "Lime Juice"]
方法二:数组API链式调用(简洁优雅)
如果你喜欢更简洁的写法,可以用Array.from结合filter,一行代码搞定:
const strIngredients = Array.from({ length: 15 }, (_, index) => { // index从0开始,所以要+1对应strIngredient1到15 return drink[`strIngredient${index + 1}`]; }) // 过滤掉空值和纯空格的食材 .filter(ingredient => ingredient && ingredient.trim() !== "");
额外提示
如果API返回的是多个饮品的数组(比如搜索结果),只需要在外层加个map遍历每个饮品即可:
// 假设API返回的饮品数组存在drinks变量中 const drinks = [/* 多个饮品对象 */]; // 生成每个饮品对应的非空食材数组 const allDrinkIngredients = drinks.map(drink => { return Array.from({ length: 15 }, (_, i) => drink[`strIngredient${i + 1}`]) .filter(ingredient => ingredient && ingredient.trim() !== ""); });
这样处理后,你就能得到每个饮品对应的有序非空食材数组,直接在页面上渲染就好啦!
内容的提问来源于stack exchange,提问作者Chan Sol Park




