返回json对象中最匹配的值

var jsonObj = [
    {
        id: 1,
        name: '首页',
        path: '/dashboard',
        children: []
    },
    {
        id: 2,
        name: '权限',
        path: '/auth',
        children: [
            {
                id: 3,
                name: '角色',
                path: '/auth/role',
                children: [
                ]
            }
        ]
    }
]
var pathStr = '/auth/role/list'

有上面两个变量jsonObj和pathStr,如果在jsonObj中有path属性对应的值和pathStr相同的,那么就返回pathStr,如果没有相同的,就找和pathStr最接近的,比如在此例中最终返回的是'/auth/role'

阅读 2k
3 个回答
function trans (arr, path, cur) {
    cur = cur || ''
    for (let i = 0, len = arr.length; i < len; i++) {
        let name = arr[i].path
        if (path.startsWith(name)) {
            let children = arr[i].children
            let result = children && children.length ? trans(children, path, name) : name
            if (result === path) return path
            if (result.length > cur.length) cur = result
        }
    }
    return cur
}
trans(jsonObj, pathStr)

比较乱,我也不知道自己写的啥东西

var pathStrArr = pathStr.split('/')
var key1 = 0;
var key2 = 0;

var a = {
  path:'',
  search:function(obj){
      var that = this;
    obj.forEach(function(i){
        console.log(i.path);
        var iArr = (i.path).split('/')
        for(var j in iArr){
          if(iArr[j] == pathStrArr[j])
           key1++;
         }
        if(key1>key2){
          this.path = i.path;
          key2 = key1;
          key1 = 0;
          
        }
        if(i.children){
          that.search(i.children);
        }
      });  
  }
}

a.search(jsonObj)
console.log(path)

https://codepen.io/jx915/pen/...

DFS 思路供参考

function matchPath (pathSrc, jsonObj) {
  let bestMatch = ''
  _match(jsonObj)
  return bestMatch

  function _match (list) {
    if (!Array.isArray(list)) { return }
    for (let i = 0; i < list.length; i++) {
      const { path = '', children } = list[i]
      if (path === pathSrc) {
        bestMatch = pathSrc
        return
      }
      if (pathSrc.startsWith(path) && path.length > bestMatch.length) {
        bestMatch = path
      }
      if (children) {
        _match(children)
      }
    }
  }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题