如何仅使用匹配路径进行过滤?

时间:2018-06-02 19:08:04

标签: javascript node.js

尝试仅根据索引路径过滤子路由。

在下面的示例中,一切正常但我们不希望输出中有任何属于/ab的路由。

function getRoutes(path: string, routerData) {
    return Object.keys(routerData).filter(routePath => {
        console.log('routePath', routePath.indexOf(path));
        return routePath.indexOf(path) === 0 && routePath !== path;
    });
}

routerData = {
 ['/a']: {},
  ['/a/1]: {},
  ['/a/2]: {},
  ['/b/1]: {},
 ['/b/2]: {},
 ['/ab/2/1]: {},
}

期待结果

 const result = ['/a/1', '/a/2'];
        expect(getRoutes('/a', routerData).map(item => item.path)).toEqual(result);

 Expected value to equal:

  ["/a/1", "/a/2"]
Received:
  ["/a/1", "/a/2", "/ab/2/1"]

1 个答案:

答案 0 :(得分:0)

您的功能会匹配以/a开头的所有路线,但不限于/a。所以你也得到/a1

为避免这种情况,您需要检查所有以/a/开头的路线:

function getRoutes(path: string, routerData) {
    if (path[path.length-1] !== '/')
        path += '/'; // Add a '/' to exclude incomplete paths
    return Object.keys(routerData).filter(routePath => {
        console.log('routePath', routePath.indexOf(path));
        return routePath.indexOf(path) === 0; // This becomes useless: && routePath !== path;
    });
}