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
相关产品推荐
相关产品推荐

