返回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'


慕婉清6462132
浏览 470回答 3
3回答

心有法竹

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

繁华开满天机

DFS 思路供参考function matchPath (pathSrc, jsonObj) {&nbsp; let bestMatch = ''&nbsp; _match(jsonObj)&nbsp; return bestMatch&nbsp; function _match (list) {&nbsp; &nbsp; if (!Array.isArray(list)) { return }&nbsp; &nbsp; for (let i = 0; i < list.length; i++) {&nbsp; &nbsp; &nbsp; const { path = '', children } = list[i]&nbsp; &nbsp; &nbsp; if (path === pathSrc) {&nbsp; &nbsp; &nbsp; &nbsp; bestMatch = pathSrc&nbsp; &nbsp; &nbsp; &nbsp; return&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; if (pathSrc.startsWith(path) && path.length > bestMatch.length) {&nbsp; &nbsp; &nbsp; &nbsp; bestMatch = path&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; if (children) {&nbsp; &nbsp; &nbsp; &nbsp; _match(children)&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript