如何检查customConfig对象中base_path对应值是否包含指定字符串
实现方法
你可以通过遍历customConfig下的所有子配置项,匹配base_path的值实现需求,直接返回布尔值:
完全匹配目标字符串的实现代码
// 入参说明:targetStr为要查找的字符串,config为你的配置对象 const checkBasePathExist = (targetStr, config) => { return Object.values(config.customConfig).some(configItem => configItem?.base_path === targetStr); } // 调用示例 const yourConfig = { "customConfig": { "homepage": { "url": "path/to/homepage", "base_path": "www.stackoverflow.com" }, "portfolio": { "url": "path/to/portfolio", "base_path": "www.github.com" }, "moreStuff": { //... } } } // 测试查找www.github.com console.log(checkBasePathExist('www.github.com', yourConfig)) // 输出 true
模糊匹配(仅判断包含目标字符串)的实现代码
把判断条件换成includes即可:
const checkBasePathInclude = (targetStr, config) => { return Object.values(config.customConfig).some(configItem => configItem?.base_path?.includes(targetStr)); }
说明
Object.values()可以直接拿到customConfig下所有子配置的对象集合Array.some()遍历只要匹配到符合条件的项就会直接终止遍历,性能开销小- 可选链
?.用来规避子配置不存在base_path属性时报错的问题
内容的提问来源于stack exchange,提问作者Codehan25
相关产品推荐
相关产品推荐

