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

如何用完整文件路径匹配对象存储的父路径并返回对应键

路径前缀匹配实现方案

核心逻辑是利用String.prototype.startsWith()做前缀校验,同时补全路径分隔符避免半匹配问题,完全规避includes/indexOf容易出现的中间内容误匹配问题。

实现代码

function getMatchedProjectKey(filePath, projects) {
  for (const [projectKey, parentPath] of Object.entries(projects)) {
    // 先移除父路径末尾多余的/,再统一补后缀/,避免半匹配(如a/b误匹配a/bc)
    const prefix = `${parentPath.replace(/\/+$/, '')}/`;
    // 匹配规则:文件路径以前缀开头,或文件路径和父路径完全相等
    if (filePath.startsWith(prefix) || filePath === parentPath) {
      return projectKey;
    }
  }
  // 无匹配返回undefined,可按需调整为null等自定义返回值
  return undefined;
}

测试验证

const projects = {
  "just-a-library": "libs/shared/util/something",
  "project-backend": "apps/project/backend"
}

// 测试示例路径
console.log(getMatchedProjectKey("libs/shared/util/something/tsconfig.spec.json", projects)) 
// 输出:just-a-library
console.log(getMatchedProjectKey("apps/project/backend/subfolder/project.json", projects)) 
// 输出:project-backend
console.log(getMatchedProjectKey("this/has/no/match.json", projects)) 
// 输出:undefined
console.log(getMatchedProjectKey("root-file.json", projects)) 
// 输出:undefined

兼容说明

如果需要适配Windows路径(分隔符为\),可以在匹配前先把所有路径的分隔符统一替换为/再执行校验逻辑即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 02:06:05