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

在JavaScript(Vue.js)中按多种菜系筛选地点

按多菜系筛选餐厅数组的解决方案

核心思路

要筛选出包含至少一个目标菜系的餐厅,需要两层检查:

  • 外层用filter()遍历所有餐厅,留下符合条件的项
  • 内层用some()检查当前餐厅的菜系列表中,是否有任意一个菜系名称存在于请求的菜系数组中

基础实现代码

const requestedCuisines = ["european", "seafood"];
const restaurants = [
  {
    "name": "Restaurant A",
    "rating": 5,
    "cuisines": [
      {"name": "spanish", "localized_name": null},
      {"name": "scandinavian", "localized_name": null},
      {"name": "european", "localized_name": "Europees"}
    ]
  },
  {
    "name": "Restaurant B",
    "rating": 5,
    "cuisines": [{"name": "spanish", "localized_name": null}]
  },
  {
    "name": "Restaurant C",
    "rating": 5,
    "cuisines": []
  }
];

// 筛选逻辑
const filteredRestaurants = restaurants.filter(restaurant => {
  // 检查当前餐厅的菜系中是否有匹配请求的项
  return restaurant.cuisines.some(cuisine => {
    return requestedCuisines.includes(cuisine.name);
  });
});

console.log(filteredRestaurants); // 输出仅包含Restaurant A的数组

代码解释

  • restaurants.filter(...):遍历所有餐厅,只保留返回true的餐厅
  • restaurant.cuisines.some(...):对当前餐厅的每个菜系进行检查,只要有一个菜系的name在requestedCuisines里,就返回true
  • requestedCuisines.includes(cuisine.name):判断单个菜系名称是否在请求列表中

优化方案(适用于大量数据)

如果请求的菜系数量很多,或者餐厅数据量很大,可以把requestedCuisines转换成Set,提升查找效率:

const requestedCuisineSet = new Set(requestedCuisines);

const filteredRestaurants = restaurants.filter(restaurant => {
  return restaurant.cuisines.some(cuisine => requestedCuisineSet.has(cuisine.name));
});

Set的has()方法比数组的includes()查找速度更快,适合处理大规模数据。

为什么你的原代码不生效?

你之前写的locations.filter(f => form.cuisines.indexOf(f.cuisines) !== -1)存在两个问题:

  1. f.cuisines是一个对象数组,而indexOf()只能查找原始值(比如字符串、数字),无法直接比较两个数组或对象
  2. 逻辑错误:你应该检查餐厅的每个菜系名称是否在请求列表里,而不是直接比较整个菜系数组

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 06:10:29