3 回答
TA贡献1866条经验 获得超5个赞
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)
TA贡献1816条经验 获得超4个赞
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)
}
}
}
}
添加回答
举报