如何用JavaScript从接口返回的数组中获取特定菜单的指定标签值?
获取特定菜单标签值的最优JavaScript实现方案
给定你从接口获取的菜单数据结构:
const menuData = [ { "title": "11-07 - 11-08", "weekhit": "Weekhit from 11-07-08", "days": { "Monday, 2022-11-07": { "Lunchmenue": "Lunchmenue from Monday 11-07", "Vegimenue": "Vegimenue from Monday 11-07" }, "Tuesday, 2022-11-08": { "Lunchmenue": "Lunchmenue from Tuesday 11-08", "Vegimenue": "Vegimenue from Tuesday 11-08" } } }, { "title": "11-14 - 11-15", "weekhit": "Weekhit from 11-14-15", "days": { "Monday, 12022-11-14": { "Lunchmenue": "Lunchmenue from Monday 11-14", "Vegimenue": "Vegimenue from Monday 11-14" }, "Tuesday, 2022-11-15": { "Lunchmenue": "Lunchmenue from Tuesday 11-15", "Vegimenue": "Vegimenue from Tuesday 11-15" } } } ];
核心实现方案:封装可复用查询函数
针对你的需求,最优方案是封装一个灵活的查询函数,既能精准定位目标数据,又具备容错性,同时支持复用。
function getMenuValue(menuData, targetDate, menuType) { // 遍历每周数据,找到包含目标日期的周 for (const week of menuData) { // 从days的键中匹配包含目标日期的条目 const matchedDayKey = Object.keys(week.days).find(key => key.includes(targetDate)); if (matchedDayKey) { // 返回对应菜单类型的值,不存在则返回null避免报错 return week.days[matchedDayKey][menuType] ?? null; } } // 未找到匹配项时返回null return null; }
函数优势
- 灵活性:通过参数指定目标日期和菜单类型,适配各种查询场景
- 容错性:找不到匹配项时返回
null,不会抛出Cannot read property of undefined错误 - 高效性:遍历到包含目标日期的周后立即停止,无需遍历全部数据
使用示例
// 查询2022-11-07的午餐菜单 const mondayLunch = getMenuValue(menuData, '2022-11-07', 'Lunchmenue'); console.log(mondayLunch); // 输出: "Lunchmenue from Monday 11-07" // 查询2022-11-15的素食菜单 const tuesdayVegi = getMenuValue(menuData, '2022-11-15', 'Vegimenue'); console.log(tuesdayVegi); // 输出: "Vegimenue from Tuesday 11-15" // 查询不存在的日期,返回null const invalidDateMenu = getMenuValue(menuData, '2022-11-09', 'Lunchmenue'); console.log(invalidDateMenu); // 输出: null
进阶优化:精准日期匹配
如果日期格式固定为"星期, YYYY-MM-DD",可以用更精准的后缀匹配避免日期子串冲突:
const matchedDayKey = Object.keys(week.days).find(key => key.endsWith(targetDate));
批量查询场景
如果需要获取所有同类型菜单(比如所有素食菜单),可以扩展另一个函数:
function getAllMenusByType(menuData, menuType) { const result = []; for (const week of menuData) { // 遍历每周的所有日期菜单 for (const [dayName, menus] of Object.entries(week.days)) { if (menus[menuType]) { result.push({ date: dayName, menu: menus[menuType] }); } } } return result; } // 获取所有素食菜单 const allVegimenus = getAllMenusByType(menuData, 'Vegimenue'); console.log(allVegimenus);
内容的提问来源于stack exchange,提问作者siga
相关产品推荐
相关产品推荐

