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

Vue.js中如何对比数组与配置对象以获取匹配的对应key

实现代码

// 你的配置对象
const config = {
  "product_hot": {
    "default": {
      "name": "Rose",
      "values": [
        "product_rose",
        "product_default"
      ]
    },
    "exclusive": {
      "name": "Cherry Blossom",
      "values": [
        "product_cherryBlossom",
        "product_exclusive",
      ]
    }
  },
}

// 数据库查询返回的数组
const productType = this.productType // 示例值:['product_cherryBlossom', 'product_cherryBlossom']

// 去重查询结果,避免重复判断
const uniqueTypes = [...new Set(productType)]

// 查找匹配的配置key
const matchedKey = Object.keys(config.product_hot).find(configKey => {
  const currentValues = config.product_hot[configKey].values
  // 判断当前配置的values是否包含所有查询到的类型值
  return uniqueTypes.every(type => currentValues.includes(type))
})

console.log(matchedKey) // 输出:exclusive

逻辑说明

  • 首先对查询返回的productType做去重处理,过滤重复值,减少不必要的判断,提升性能
  • 用Object.keys获取配置项product_hot下的所有一级key(也就是default、exclusive)
  • 用find遍历所有key,返回第一个符合匹配规则的key:
    • 现在用的every规则:要求查询数组里的所有元素都必须在当前配置的values数组中存在,才算匹配,完全符合你给出的示例场景
    • 如果你只需要values数组包含查询数组的任意一个元素就算匹配,把every替换为some即可
  • 如果存在多个符合条件的配置项,想要获取所有匹配的key,把find替换为filter即可,返回结果为匹配key组成的数组

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 10:06:00